python - Pandas 标准化或标准化按类别分组
问题描述
给定数据框 df 计算为
df = pd.DataFrame.from_dict({
'type': ['a','b','c','a','b','c','a','b','c','a','a','b','c','a','b','c','a','b','c','a','a','b','c','a','b','c','a','b','c','a'],
'x1': np.random.rand(30), #np.arange(10),
'x2': np.random.rand(30)/2
})
df['x3'] = df.x1 > df.x2
df['x1']=df.apply(lambda x: x['x1']*2 if x['type']=='a' else x['x1'], axis=1)
df['x1']=df.apply(lambda x: x['x1']+10 if x['type']=='b' else x['x1'], axis=1)
df['x2']=df.apply(lambda x: x['x2']*x['x2'] if x['type']=='c' else x['x2'], axis=1)
df = df.append(df).reset_index(drop=True)
df = df.append(df).reset_index(drop=True)
df
如何对数字列进行规范化/标准化,即“X1”和“X2”,按类别列“类型”分组?换句话说,'type' =='b' 不能干扰 'type' !='b' 的数据的规范化。
输出 df 具有相同的列,但 X1 和 X2 被转换为标准化或标准化的 X1 和 X2。
解决方案
您可以过滤数字列,然后使用groupby().apply()
:
# select the number columns
num_cols = df.select_dtypes(include=np.number).columns
def normalize(x):
return (x-x.min())/(x.max()-x.min())
normalized = df.groupby('type')[num_cols].apply(normalize)
# check
normalized.agg(['min','max'])
输出:
x1 x2
min 0.0 0.0
max 1.0 1.0
推荐阅读
- yii2 - 如何在 Yii2 中重置模型以添加新/下一条记录?
- git - git-flow 在提高 MR 进行代码审查时是不是有点模棱两可?
- java - 使用 Java Hibernate 从 MySQL 数据库中检索多行并将其存储在变量中
- java - 类文件中的 InnerClass 属性有什么用?
- c# - 如何在 Unity 中使用 C# 代码在移动设备上工作?
- c# - serializedObject 变为 null 错误
- python - 如何创建一个新列,将前 5 行和剩余的行合并为杂项?
- c++ - 使用模板向上转换 unique_ptr
- spring-boot - 插入两个集合而不阻塞
- android - getString() 与路径连接?