如何在忽略负数的情况下计算中位数?

huangapple go评论110阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 19:20:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定