我的数据框不完整incomplete_df
,如下所示。我想将丢失的amount
与相应的amount
的平均值id
归为一类。如果特定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方式是什么?
答案 0 :(得分:17)
免责声明:我对最快速的解决方案并不感兴趣,但最为宽松。
在这里,我认为这将是:
>>> df["amount"].fillna(df.groupby("id")["amount"].transform("mean"), inplace=True)
>>> df["amount"].fillna(df["amount"].mean(), inplace=True)
产生
>>> df
id type amount
0 1 one 345.0
1 2 one 928.0
2 3 two 942.0
3 2 three 645.0
4 2 two 113.0
5 3 three 942.0
6 1 one 442.0
7 1 two 539.0
8 1 one 442.0
9 2 three 814.0
10 4 one 615.2
[11 rows x 3 columns]
有很多明显的调整取决于你想要链式插补过程的确切方式。