python - 在有效条件后选择数据框中的行数
问题描述
我想在验证条件后选择指定数量的行:
- 这是我的数据框:
- 我想在条目等于 1 之后选择三列,所以对于第一次出现我会得到类似的东西:
- 如果我想研究每一个事件,也许是 groupby ,我不知道最合适的输出是什么?
解决方案
首先删除0
first 之前的行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
- 所以在操作后过滤掉所有0
值cumsum
:
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
助手过滤后:Series
sum
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
的值:4
1
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())]
推荐阅读
- postgresql - 如何设置表默认 autovacuum_analyze_threshold
- python - 如何在 django 序列化程序中进行验证?
- java - 如何定义到 InfluxDB 的 Apache Camel 路由
- java - 如何更新 Dynamo DB 中保留关键字的值。错误:属性名称是保留关键字;保留关键字:数据
- android - 在限制线之间绘制背景颜色
- c# - 如何在多个线程中正确锁定对列表的访问
- c# - 为 linq join 创建自定义比较器的正确方法
- google-cloud-platform - 如何在 GCE 上禁用 windows server 2016 自动更新
- unity3d - MRTK V2 - Toggle-Dot 移动到约束之外
- node.js - 如何判断 TLS 服务器是否请求了客户端证书