python - Pandas :估算 NaN 的

标签 python pandas nan dataframe mean

我有一个不完整的数据框,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/

相关文章:

python - python 中共享迭代器的两个数据结构

python - 全局名称 '...' 未定义

python - 根据唯一条目的数量按组计算比例

python - 在python中将 "nan"移到数组的开头

elasticsearch - 使用NaN值对百分位数聚合排序

python - 在xarray中取一个 "nanmean"

javascript - 使用 python selenium 从 javascript 链接下载 csv 文件

python - 将数据从 excel 电子表格导入到 django 模型

python - 将字符串头和索引添加到 numpy 数组

python - 如何根据 Pandas 中的列值选择行