簡體   English   中英

如何使用熊貓中的for循環根據另一列的條件填充一列中的缺失值?

[英]How to fill in missing values in one column based on a condition form another column using for loops in pandas?

weather_train=pd.DataFrame({
'site_id':[0,0,0,0,0,0,1,1,1,1,1],
'air_temperature': [25,22,'NaN',28,'NaN',30,45,'NaN',50,'Nan',24]
})
  • site_id是0,我需要計算的平均air_temperaturesite_id 0,然后用平均填補了缺失值air_temperaturesite_id 0。
  • 然后,當site_id是1,我需要計算的平均air_temperature為SITE_ID在失蹤值1和填充air_temperature在SITE_ID 1。

必須對cloud_coverage執行相同的過程。

任何人都可以幫我在 Pandas 中為此編寫一個 for 循環嗎?

不需要循環。 只需將groupby().transform()用於包含在條件numpy.where中的內聯平均聚合:

weather_train['air_temperature'] = np.where(pd.isnull(weather_train['air_temperature']),
                                            weather_train.groupby(['site'])['air_temperature'].transform('mean'),    
                                            weather_train['air_temperature'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM