【发布时间】:2019-08-16 10:10:37
【问题描述】:
我正在尝试仅使用 numpy 计算正负和无条纹。这个问题我必须弄清楚我所有的研究都认为我需要的方程的 groupby 分量。我在这里找到了熊猫回复Pythonic way to calculate streaks in pandas dataframe
我已经能够转换除 groupby 片段之外的所有片段。任何帮助表示赞赏
这是我想复制的熊猫代码。唯一的非 numpy 等价物是 groupby。我还在 numpy 中创建了自己的 shift 函数。
熊猫版:
def streaks(df, col):
sign = np.sign(df[col])
s = sign.groupby((sign!=sign.shift()).cumsum()).cumsum()
return df.assign(u_streak=s.where(s>0, 0.0),
d_streak=s.where(s<0,0.0).abs())
我的部分 numpy 版本:
arr = np.array([0.2,0.1,0.1,0.0,-0.2,-0.1,0.0])
sign = np.sign(arr)
s = np.not_equal(sign, shift(sign))
# now I need to groupby and then sum and sum again
np.cumsum(groupby(np.cumsum(s)))
预期的结果应该是:
array([1.,2.,3.,0.,-1.,-2.,0.])
【问题讨论】:
标签: python numpy pandas-groupby