首页 > 解决方案 > 在有效条件后选择数据框中的行数

问题描述

我想在验证条件后选择指定数量的行:

在此处输入图像描述

在此处输入图像描述

标签: pythonpandasnumpydataframe

解决方案


首先删除0first 之前的行1

df = df[df['entry'].eq(1).cumsum().ne(0)]

df = df.groupby(df['entry'].cumsum()).head(4)
    Timestamp  entry
1        11.2      1
2        11.3      0
3        11.4      0
4        11.5      0
7        11.8      1
8        11.9      0
9        12.0      0
10       12.1      0

详情及说明

对于在第一次匹配之前删除所有值的一般解决方案是使用 compare by Series.eq,然后是累积 sum bySeries.cumsum和 compare by Series.ne- 所以在操作后过滤掉所有0cumsum

print (df.assign(comp1 = df['entry'].eq(1),
                 cumsum =df['entry'].eq(1).cumsum(),
                 mask = df['entry'].eq(1).cumsum().ne(0)))
    Timestamp  entry  comp1  cumsum   mask
0        11.1      0  False       0  False
1        11.2      1   True       1   True
2        11.3      0  False       1   True
3        11.4      0  False       1   True
4        11.5      0  False       1   True
5        11.6      0  False       1   True
6        11.7      0  False       1   True
7        11.8      1   True       2   True
8        11.9      0  False       2   True
9        12.0      0  False       2   True
10       12.1      0  False       2   True

通过创建具有累积的组的boolean indexing助手过滤后:Seriessum

print (df['entry'].cumsum())
1     1
2     1
3     1
4     1
5     1
6     1
7     2
8     2
9     2
10    2
Name: entry, dtype: int64

因此,对于最终解决方案,使用获取行和下 3 行GroupBy.head的值:41

df = df.groupby(df['entry'].cumsum()).head(4)
print (df)
    Timestamp  entry
1        11.2      1
2        11.3      0
3        11.4      0
4        11.5      0
7        11.8      1
8        11.9      0
9        12.0      0
10       12.1      0

对于按组循环使用:

for i, g in df.groupby(df['entry'].cumsum()): 
    print (g.head(4))

如果想要 s 的输出列表DataFrame

L = [g.head(4) for i, g in df.groupby(df['entry'].cumsum())]

推荐阅读