1 回答
TA贡献1876条经验 获得超5个赞
使用Series.fillnawithSeries.map替换匹配值 by area:
df['number'] = df['number'].fillna(df['area'].map(Hell.set_index('area')['number']))
print (df)
area number
0 abc 1.0
1 abc 2.0
2 abc 2.0
3 abc 2.0
4 bcd 3.0
5 bcd 3.0
6 bcd 3.0
7 cde 5.0
8 cde 5.0
9 cde 4.0
10 cde 5.0
11 cde 5.0
或者将您的解决方案GroupBy.transform用于相同的系列,例如由聚合值填充的原始系列:
s = df.groupby("area")['number'].transform(lambda x: x.value_counts().index[0])
#alternative
#s = df.groupby("area")['number'].transform(lambda x: x.mode().iat[0])
df['number'] = df['number'].fillna(s)
print (df)
area number
0 abc 1.0
1 abc 2.0
2 abc 2.0
3 abc 2.0
4 bcd 3.0
5 bcd 3.0
6 bcd 3.0
7 cde 5.0
8 cde 5.0
9 cde 4.0
10 cde 5.0
11 cde 5.0
添加回答
举报