检查 pandas 数据框的最后几行是否满足一组条件的最佳方法是什么? [英] What is the best way to check if the last rows of a pandas dataframe meet a set of conditions?

查看:59
本文介绍了检查 pandas 数据框的最后几行是否满足一组条件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是以下问题的后续内容:

This question is a follow-up of the follow question: What is the best way to check if the last rows of a pandas dataframe meet a condition?

但是我在尝试修改提供的答案以满足我的需求时遇到了麻烦。

But I got stuck trying to modify the answers provided to meet my needs.

条件01 =如果最后五个(5 )连续的 singal 行(包括最后一行)为1,则将返回1。

Criteria 01 = If the last five (5) consecutive rows(including the last) of singal are 1, it would return 1.

条件02 =如果 singal 的最后三(3)个连续行(包括最后一个)为0,它将返回0。

Criteria 02 = If the last three (3) consecutive rows(including the last) of singal are 0, it would return 0.

条件03 =在条件01或条件02第一次见面之前,它将返回 nan

Criteria 03 = Before the first meet of CRITERIA 01 or CRITERIA 02, it would return nan.

条件04 =其他所有内容都是支票的最后价值。

Criteria 04 = Everything else would be the last value of check.

像这样:

index   signal  check
0       1       nan
1       1       nan
2       1       nan
3       1       nan
4       1       1
5       1       1
6       0       1
7       0       1
8       0       0
9       0       0
10      0       0
11      1       0
12      0       0
13      1       0
14      0       0
15      1       0
16      1       0
17      1       0
18      1       0
19      1       1

I会感谢您的帮助!

谢谢!

推荐答案

您还需要另外进行 rolling(3)

m1 = df.rolling(5).sum().eq(5)
m2 = df.eq(0).rolling(3).sum().eq(3)
df['check'] = df[m1 | m2].ffill()

Out[310]:
       signal  check
index
0           1    NaN
1           1    NaN
2           1    NaN
3           1    NaN
4           1    1.0
5           1    1.0
6           0    1.0
7           0    1.0
8           0    0.0
9           0    0.0
10          0    0.0
11          0    0.0
12          0    0.0
13          1    0.0
14          0    0.0
15          1    0.0
16          1    0.0
17          1    0.0
18          1    0.0
19          1    1.0






面具 m2 也可以简化为

m2 = df.rolling(3).sum().eq(0)

这篇关于检查 pandas 数据框的最后几行是否满足一组条件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆