假设我有一个数据帧df,其中包含列"事物;以及";值";,但我想制作一个新的专栏";归一化的";其中值除以值的平均值";";
所以
事物 | 类型 | 值 | |
---|---|---|---|
a | t1 | <1>||
a | t1 | 2 | |
a | t1 | 6 | |
b | t1 | <2>||
b | t1 | 4//tr>||
b | t1 | 9 | |
a | t2 | 4 | |
a | t2 | 9 | |
a | t2 | 5 |
对于与原始列大小相同的系列使用GroupBy.transform
,因此可能的划分:
df['norm'] = df['value']/df.groupby(['thing', 'type'])['value'].transform('mean')
print (df)
thing type value norm
0 a t1 1 0.333333
1 a t1 2 0.666667
2 a t1 6 2.000000
3 b t1 2 0.400000
4 b t1 4 0.800000
5 b t1 9 1.800000
6 a t2 4 0.666667
7 a t2 9 1.500000
8 a t2 5 0.833333
详细信息:
print (df.groupby(['thing', 'type'])['value'].transform('mean'))
0 3
1 3
2 3
3 5
4 5
5 5
6 6
7 6
8 6
Name: value, dtype: int64