我想用另一列分组的列的均值(不带零)替换数据帧的列值。
数据框 df 类似于:
ID | TYPE | rate
-------------
1 | A | 0 <- Replace this
2 | B | 2
3 | C | 1
4 | A | 2
5 | C | 1
6 | C | 0 <- Replace this
7 | C | 8
8 | C | 2
9 | D | 0 <- Replace this
我必须替换等级为0的等级中的值:
df['rate'][df['rate']==0] = ?
具有该 TYPE 的平均值。
每种类型的Average(不带零)值是:
A = 2/1 = 2
B = 2/1 = 2
C =(1 +1 + 8 + 2)/ 4 = 3
D = 0(没有类型信息时为默认值)
预期结果:
ID | TYPE | rate
-------------
1 | A | 2 <- Changed
2 | B | 2
3 | C | 1
4 | A | 2
5 | C | 1
6 | C | 3 <- Changed
7 | C | 8
8 | C | 2
9 | D | 0 <- Changed