gpt4 book ai didi

python - Pandas - 用特定组的平均值替换列中的 NaN

转载 作者:行者123 更新时间:2023-11-28 21:31:34 25 4
gpt4 key购买 nike

我正在处理如下数据。数据框按日期排序:

category  value  Date
0 1 24/5/2019
1 NaN 24/5/2019
1 1 26/5/2019
2 2 1/6/2019
1 2 23/7/2019
2 NaN 18/8/2019
2 3 20/8/2019
7 3 1/9/2019
1 NaN 12/9/2019
2 NaN 13/9/2019

我想用该特定类别的先前平均值替换“NaN”值。

在 pandas 中执行此操作的最佳方法是什么?

我考虑过的一些方法:

1) 这个小重复段:

   df['mean' = df.groupby('category')['time'].apply(lambda x: x.shift().expanding().mean()))

source

这让我得到了正确的方法,但在另一列中,它并没有取代 NaN。

2) 此 riff 将 NaN 替换为列的平均值:

df = df.groupby(df.columns, axis = 1).transform(lambda x: x.fillna(x.mean()))

Source 2

这两个都不完全符合我的要求。如果有人可以指导我,我将不胜感激!

最佳答案

您可以用 shift + expanding + mean 的新系列替换 value 的第一个值>1 组未被替换,因为没有先前的 NaN 值存在:

df['Date'] = pd.to_datetime(df['Date'])
s = df.groupby('category')['value'].apply(lambda x: x.shift().expanding().mean())
df['value'] = df['value'].fillna(s)
print (df)
category value Date
0 0 1.0 2019-05-24
1 1 NaN 2019-05-24
2 1 1.0 2019-05-26
3 2 2.0 2019-01-06
4 1 2.0 2019-07-23
5 2 2.0 2019-08-18
6 2 3.0 2019-08-20
7 7 3.0 2019-01-09
8 1 1.5 2019-12-09
9 2 2.5 2019-09-13

关于python - Pandas - 用特定组的平均值替换列中的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943625/

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