首页 > 解决方案 > 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。

标签: pythonpandas

解决方案


您可以过滤数字列,然后使用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

推荐阅读