英文:
How to calculate median while ignoring negative values?
问题
我有以下的数据框:
y
-1
-1
2
3
2
1
0
我需要应用一个窗口大小为3的滚动窗口,并计算中位数,同时忽略负值(例如 -1
)。我应该如何做?
这是我尝试过的方法:
window = 3
y.rolling(window)[y >= 0].apply(lambda x: np.median(x)).dropna()
英文:
I have the following dataframe:
y
-1
-1
2
3
2
1
0
I need to apply a rolling window of 3 and calculate a median, while ignoring negative (e.g. -1
) values. How can I do so?
This is what I tried:
window = 3
y.rolling(window)[y>=0].apply(lambda x: np.median(x)).dropna()
答案1
得分: 1
在lambda函数中筛选或在之前筛选,但输出不同
window = 3
df['new1'] = df.y.rolling(window).apply(lambda x: np.median([x >= 0]), raw=False)
df['new2'] = df.loc[df.y >= 0, 'y'].rolling(3).median()
print(df)
y new1 new2
0 -1 NaN NaN
1 -1 NaN NaN
2 2 0.0 NaN
3 3 1.0 NaN
4 -2 1.0 NaN
5 -1 0.0 NaN
6 0 0.0 2.0
英文:
Filter in lambda function or filter before, but output is different
window = 3
df['new1'] = df.y.rolling(window).apply(lambda x: np.median([x>=0]), raw=False)
df['new2'] = df.loc[df.y>=0, 'y'].rolling(3).median()
print (df)
y new1 new2
0 -1 NaN NaN
1 -1 NaN NaN
2 2 0.0 NaN
3 3 1.0 NaN
4 -2 1.0 NaN
5 -1 0.0 NaN
6 0 0.0 2.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论