我有一个不完整的数据框,incomplete_df
,如下所示。我想用相应id
的平均金额来填充缺失的amount
。 如果该特定id
的平均值本身为NaN(见id=4
),我希望使用总体平均值。
以下是示例数据和我极低效的解决方案:
import pandas as pd
import numpy as np
incomplete_df = pd.DataFrame({'id': [1,2,3,2,2,3,1,1,1,2,4],
'type': ['one', 'one', 'two', 'three', 'two', 'three', 'one', 'two', 'one', 'three','one'],
'amount': [345,928,np.NAN,645,113,942,np.NAN,539,np.NAN,814,np.NAN]
}, columns=['id','type','amount'])
# Forrest Gump Solution
for idx in incomplete_df.index[np.isnan(incomplete_df.amount)]: # loop through all rows with amount = NaN
cur_id = incomplete_df.loc[idx, 'id']
if (cur_id in means.index ):
incomplete_df.loc[idx, 'amount'] = means.loc[cur_id]['amount'] # average amount of that specific id.
else:
incomplete_df.loc[idx, 'amount'] = np.mean(means.amount) # average amount across all id's
最快、最pythonic/pandonic的实现方式是什么?
NaN
,我该如何处理这种情况? - Zhubarb