Python DataFrame结合了两个布尔列
我有一个数据框。我正在向前和向后的缩写。后来,进行比较并产生布尔输出。接下来,我想执行逻辑和这些结果,并产生一个结果。
代码:
xdf = pd.DataFrame({'data':range(0,6)},index=pd.date_range('2022-06-03 00:00:00', '2022-06-03 00:00:25', freq='5s'))
# perform 1 row backward substraction
bs = xdf['data'].diff(1).abs().le(1)
# perform 1 row forward substraction
fs= xdf['data'].diff(-1).abs().le(1)
bs =
2022-06-03 00:00:00 False
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 True
Freq: 5S, Name: data, dtype: bool
fs =
2022-06-03 00:00:00 True
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 False
目前和预期输出:
xdf['validation'] = np.logical_and(sa,sb)
2022-06-03 00:00:00 False
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 False
Freq: 5S, Name: data, dtype: bool
输出是正确的,这是我期望的。我的问题是,有什么方法可以在单个行码中计算上述所有(正向缩写和向后缩)?
I have a dataframe. I am performing forward and backward substraction. Later, perform a comparison and produce boolean outputs. Next, I want to perform logical and on these results and produce one result.
Code:
xdf = pd.DataFrame({'data':range(0,6)},index=pd.date_range('2022-06-03 00:00:00', '2022-06-03 00:00:25', freq='5s'))
# perform 1 row backward substraction
bs = xdf['data'].diff(1).abs().le(1)
# perform 1 row forward substraction
fs= xdf['data'].diff(-1).abs().le(1)
bs =
2022-06-03 00:00:00 False
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 True
Freq: 5S, Name: data, dtype: bool
fs =
2022-06-03 00:00:00 True
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 False
Present and expected output:
xdf['validation'] = np.logical_and(sa,sb)
2022-06-03 00:00:00 False
2022-06-03 00:00:05 True
2022-06-03 00:00:10 True
2022-06-03 00:00:15 True
2022-06-03 00:00:20 True
2022-06-03 00:00:25 False
Freq: 5S, Name: data, dtype: bool
The output is correct and this is what I am expecting. My question, is there a way I can compute all the above (forward substraction and backward substraction) in a single code of line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您可以尝试循环
[1,-1]
并使用np.logical_and.reduce
Maybe you can try loop the
[1,-1]
and usenp.logical_and.reduce
iiuc,您可以使用滚动最大值,然后检查最大目标是否≤您的目标:
输出:
IIUC, you can use a rolling max, then check whether the max is ≤ your target:
output: