[英]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_temperature
的site_id
0,然后用平均填補了缺失值air_temperature
在site_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.