pandas - 通过布尔分隔符拆分 numpy 数组/熊猫数据帧
问题描述
假设一个 numpy 数组(实际上是 Pandas)的形式:
[value, included,
0.123, False,
0.127, True,
0.140, True,
0.111, False,
0.159, True,
0.321, True,
0.444, True,
0.323, True,
0.432, False]
我想拆分数组,以便False
排除元素并将连续运行的True
元素拆分为它们自己的数组。因此,对于上述情况,我们最终会得到:
[[0.127, True,
0.140, True],
[0.159, True,
0.321, True,
0.444, True,
0.323, True]]
我当然可以通过将单个元素推送到列表中来做到这一点,但肯定有一种更 numpy-ish 的方式来做到这一点。
解决方案
You can create groups by inverse mask by ~
with Series.cumsum
and filter only True
s by boolean indexing
, then create list of DataFrame
s by DataFrame.groupby
:
dfs = [v for k, v in df.groupby((~df['included']).cumsum()[df['included']])]
print (dfs)
[ value included
1 0.127 True
2 0.140 True, value included
4 0.159 True
5 0.321 True
6 0.444 True
7 0.323 True]
Also is possible convert Dataframes to arrays by DataFrame.to_numpy
:
dfs = [v.to_numpy() for k, v in df.groupby((~df['included']).cumsum()[df['included']])]
print (dfs)
[array([[0.127, True],
[0.14, True]], dtype=object), array([[0.159, True],
[0.321, True],
[0.444, True],
[0.32299999999999995, True]], dtype=object)]
推荐阅读
- java - 如何在 firebase 数据库中检索特定子项的数据 - android studio/java?
- vue.js - EBADCSRFTOKEN:adonis js 中的无效 CSRF 令牌
- terraform - Terraform:为多个实例创建 CloudWatch 警报时出错
- angular - 尝试过滤 *ngFor 指令中的数据
- javascript - 我可以判断屏幕是否关闭与浏览器最小化或标签是否已用 js 更改?
- angular - Angular Material Button Toggle 在布局/视图之间切换
- python - 如何找到 numpy 轴上的最终累积总和?
- rust - 如何为使用生命周期实现的特征传递函数?
- swagger - 大摇大摆的模式数组
- for-loop - 嵌套 For 循环 astrix 模式