假定以下形式的numpy数组(实际上是熊猫):
[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]]
我当然可以通过将单个元素推送到列表上来做到这一点,但是肯定必须有一种更加麻木的方式来做到这一点。
答案 0 :(得分:1)
您可以使用~
和Series.cumsum
通过反掩码创建组,并通过boolean indexing
仅过滤True
s,然后通过{创建DataFrame
s列表{3}}:
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]
还可以通过DataFrame.groupby
将数据框转换为数组:
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)]