for section_value in sorted(set(df.Section)):
df.loc[df['Section']==section_value, 'Price'] = df.loc[df['Section']==section_value, 'Price'].fillna(df.loc[df['Section']==section_value, 'Price'].mean())
means = df.groupby('Section').Price.mean()
nulls = df.Price.isnull()
fills = df.Section[nulls].map(means)
df.loc[nulls, 'Price'] = fills
print(df)
Name Sex Section Price
0 Joe M 1 2.0
1 Bob M 1 4.0
2 Nancy F 2 5.0
3 Grace F 1 6.0
4 Jen F 2 10.0
5 Paul M 2 7.5
所谓“相应的水平”,我假设你的意思是相等的截面值。在
如果是这样,你可以通过
希望有帮助!和平
您可以使用组合}。请注意,我已经修改了您的示例,否则这两个部分的平均值相同。从开始
groupby
、transform
和{我们可以利用
^{pr2}$生产
这是因为我们可以通过截面计算平均值:
并将此广播回一个完整的系列,我们可以使用
transform
传递给fillna():pandas
外科手术,但速度较慢请参阅@DSM的答案以获得更快的
pandas
解决方案这是一种更为外科手术的方法,可能提供一些视角,可能有用
使用
groupyby
为每个
Section
计算我们的mean
识别空值
使用
isnull
可用于布尔切片使用
map
对
Section
列进行切片,将其限制为空Price
的行使用
loc
只填充
df
中有空的地方一起
相关问题 更多 >
编程相关推荐