gpt4 book ai didi

python - Pandas :估算 NaN 的

转载 作者:太空狗 更新时间:2023-10-29 20:40:48 25 4
gpt4 key购买 nike

我有一个不完整的数据框,incomplete_df,如下所示。我想用相应 id 的平均 amount 来估算缺失的 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 的方式来实现这一点?

最佳答案

免责声明:我对最快的解决方案并不感兴趣,但对最可恶的解决方案不感兴趣。

在这里,我认为应该是这样的:

>>> 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]

有很多明显的调整,具体取决于您希望链式插补过程如何进行。

关于python - Pandas :估算 NaN 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com