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

2024-03-08

我有一个数据框,如下面的 df 。我想为条件为真的每个数据块创建一个新的数据帧,以便它将返回 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     |   |   |       |   |       |

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

newdf = df.iloc[start:end]

但这样做似乎效率很低。


这是一个替代解决方案。请注意consecutive_groups http://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.consecutive_groups食谱来自更多_iter工具 http://more-itertools.readthedocs.io/en/latest/api.html图书馆。

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}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当条件为真时,Pandas 将数据帧拆分为多个 的相关文章

随机推荐