【发布时间】:2021-12-26 12:12:36
【问题描述】:
我想用同一列的下一个和上一个正数的平均值替换负数、NaN 和 0。
原始数据框
a c
0 1 1
1 2 2
2 0 5
3 -3 NaN
4 -1 5
5 3 3
预期的输出数据帧是
a c
0 1 1
1 2 2
2 2.5 5 #In Col a --> Mean of 2 and 3 is 2.5 hence 0 replaced by 2.5
3 2.75 5 #In Col a --> Mean of 2.5 and 3 is 2.75 hence negative no. replaced by 2.75
4 2.875 5 #In Col a --> Mean of 2.75 and 3 is 2.875 hence negative no. replaced by 2.875
5 3 3
我尝试了另一种策略来处理否定号。 Nan 和 0 用前 3 个值的平均值替换它
m = df['a'] < 1
new = (df.loc[~m, 'a'].astype(float)
.rolling(2, min_periods=1).mean()
.reindex(df.index, method='ffill'))
df['a'].mask(m, new)
导致
0 1.0
1 2.0
2 1.5
3 1.5
4 1.5
5 2.0
Name: a, dtype: float64
但是我正在努力实施新策略(被问到)。
【问题讨论】:
-
我没有投反对票,但我想这是因为你没有展示你尝试过和失败的东西。在要求其他人也考虑您的问题之前,很高兴表明您自己已经对问题进行了充分的思考
-
感谢@CallumDA!我已经实施了问题中添加的另一个策略,但是为了提高模型的准确性,我需要帮助来实施第二个策略。
-
好多了。现在看起来是一个好的问题。我相应地投了赞成票
标签: python python-3.x pandas replace time-series