python - 当条件为真时,Pandas 将数据帧拆分为多个

标签 python python-3.x pandas split

我有一个数据框,如下面的 df。我想为条件为真的每个数据 block 创建一个新的数据帧,以便返回 df_1、df_2....df_n。

|      df           |       |  df_1 |   | df_2  |
| Value | Condition |       | Value |   | Value |
|-------|-----------|       |-------|---|-------|
| 2     | True      |   |   | 2     |   | 0     |
| 5     | True      |   |   | 5     |   | 5     |
| 4     | True      |   |   | 4     |   |       |
| 4     | False     |   |   |       |   |       |
| 2     | False     |   |   |       |   |       |
| 0     | True      |   |   |       |   |       |
| 5     | True      |   |   |       |   |       |
| 7     | False     |   |   |       |   |       |
| 8     | False     |   |   |       |   |       |      
| 9     | False     |   |   |       |   |       |

我唯一的想法是遍历数据帧,返回每个真值 block 的开始和结束索引,然后创建新的数据帧,循环遍历返回的索引,为每个开始/结束对返回类似这样的内容:

newdf = df.iloc[start:end]

但这样做似乎效率不高。

最佳答案

这是另一种解决方案。注意 consecutive_groups食谱来自more_itertools图书馆。

from itertools import groupby
from operator import itemgetter

def consecutive_groups(iterable, ordering=lambda x: x):
    for k, g in groupby(enumerate(iterable), key=lambda x: x[0] - ordering(x[1])):
        yield map(itemgetter(1), g)

grps = consecutive_groups(df[df.Condition].index)

dfs = {i: df.iloc[list(j)] for i, j in enumerate(grps, 1)}

# {1:    Value Condition
# 0      2      True
# 1      5      True
# 2      4      True,
# 2:    Value Condition
# 5      0      True
# 6      5      True}

关于python - 当条件为真时,Pandas 将数据帧拆分为多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48770013/

相关文章:

python - 为什么 'é'和 'é'编码成不同的字节?

python - 聚合 Pandas 数据框中的单元格/列

python - 如何计算间隔序列中1小时间隔的总数?

python - 检查用python编写的配置单元udf中的错误

python - 使用 Selenium 在 Python 中抓取由 javascript 注入(inject)的图像

python - 如何从字典列表中过滤掉具有重复键和不同值的元素?

python 3 : How to move an item from list x to list y and remove it from list x?

Eclipse 中的 Python 库

python - 将 str 类型的字典转换为 float Python

python - 根据连续出现的值对数据帧进行分组