我有一个不完整的数据帧,incomplete_df
,如下所示。我想用相应的id
的平均值来估算缺失的amount
s。如果这个特定的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
实现这一目标的最快、最具Python式/泛神论的方法是什么?
免责声明:我不是真的对最快的解决方案感兴趣,而是最可悲的。
在这里,我想应该是:
产生
有很多明显的调整取决于你到底希望如何进行链式插补过程。
相关问题 更多 >
编程相关推荐