用平均值代替值
replace values by the mean
我有一个数据框如下:
Col1 Price
1 Plastic 50
2 Metal 100
3 Plastic 40
我想用 Price 中的方式替换 Col1 中的值,所以我得到:
Col1 Price
1 45 50
2 100 100
3 45 40
我已经做过了:
df.groupby('Col1').mean()['Price']
但我不知道如何替换这些值,也许使用地图?
你说得对 - map
可以这样使用:
df['Col1'] = df['Col1'].map(df.groupby('Col1')['Price'].mean())
df
Col1 Price
1 45 50
2 100 100
3 45 40
df.assign(Col1=df.Col1.map(df.groupby('Col1').mean().squeeze()))
输出:
Col1 Price
1 45 50
2 100 100
3 45 40
如果你想直接得到结果,可以使用transform
df['Col1']=df.groupby(['Col1'])['Price'].transform('mean')
Col1 Price
0 45 50
1 100 100
2 45 40
我有一个数据框如下:
Col1 Price
1 Plastic 50
2 Metal 100
3 Plastic 40
我想用 Price 中的方式替换 Col1 中的值,所以我得到:
Col1 Price
1 45 50
2 100 100
3 45 40
我已经做过了:
df.groupby('Col1').mean()['Price']
但我不知道如何替换这些值,也许使用地图?
你说得对 - map
可以这样使用:
df['Col1'] = df['Col1'].map(df.groupby('Col1')['Price'].mean())
df
Col1 Price
1 45 50
2 100 100
3 45 40
df.assign(Col1=df.Col1.map(df.groupby('Col1').mean().squeeze()))
输出:
Col1 Price
1 45 50
2 100 100
3 45 40
如果你想直接得到结果,可以使用transform
df['Col1']=df.groupby(['Col1'])['Price'].transform('mean')
Col1 Price
0 45 50
1 100 100
2 45 40