这个问题是建立在上一个问题的基础上的:create new column that compares across rows in pandas dataframe
我想创建一个新列来检查接下来的 n 行中是否有任何一行的差异超过 X。例如,如果我们有一个数据框并且接下来的 4 行的差异超过 1,那么新的值将为 0。如果接下来的 4 行相差小于或等于 1,则新值将为 1。
>>> df = pandas.DataFrame({"A": [5,6,4,3,5]})
>>> df
A
0 5
1 6
2 4
3 3
4 5
>>> desired_result = pandas.DataFrame({"A": [5,6,7,8,2], "new": [1,1,0,0,0]})
>>> desired_result
A new
0 5 1
1 6 0
2 4 1
3 3 0
4 5 0
在上面的示例中,5 的值变为 1,因为接下来两个值之间的绝对差值 <= 1(abs(5-6) = 1 和 abs(5-4) = 1)。
与上面帖子提供的答案类似,我尝试用下面的代码来解决这个问题:
df['new'] = 1
df.loc[abs(df.A - df.A.shift(-1)) > 1 , 'new'] = 0
此代码仅在查看下一行时有效,但我不确定将其扩展到 n 行的最佳方法是什么。
请您参考如下方法:
n = 2 # Number of following rows
x = 1 # Differ by more than 'x'.
>>> pd.concat([(df.A - df.A.shift(-i - 1)).abs().le(x)
for i in range(n)], axis=1).any(axis=1) * 1
0 1
1 0
2 1
3 0
4 0
dtype: int64
移位执行 n 次并与当前值进行比较,产生以下 bool 值:
# shift-1 shift-2
A A
0 True True
1 False False
2 True True
3 False False
4 False False
然后将这些结果跨行进行比较,寻找任何真实值。最后, bool 结果乘以 1 将其变成 1 和 0。
`pd.concat(...).any(axis=1) * 1`
