【问题标题】:Split dataframe according to common consecutive sequences根据公共连续序列拆分数据帧
【发布时间】:2022-12-31 05:01:06
【问题描述】:

让我们考虑这个 DataFrame :

import pandas as pd

df = pd.DataFrame({"type" : ["dog", "cat", "whale", "cat", "cat", "lion", "dog"],
                   "status" : [False, True, True, False, False, True, True],
                   "age" : [4, 6, 7, 7, 1, 7, 5]})

看起来像这样:

    type  status  age
0    dog   False    4
1    cat    True    6
2  whale    True    7
3    cat   False    7
4    cat   False    1
5   lion    True    7
6    dog    True    5

我想根据以下内容拆分此数据框连续相同的值在列状态中。 结果存储在列表中。

在这里我手动写下预期结果:

result = [df.loc[[0],:], df.loc[1:2,:], df.loc[3:4,:], df.loc[5:6,:]]

所以 result[0] 是这个数据帧:

  type  status  age
0  dog   False    4

结果 [1] 是这个数据框:

    type  status  age
1    cat    True    6
2  whale    True    7

结果 [2] 是这个数据框:

  type  status  age
3  cat   False    7
4  cat   False    1

结果 [3] 是数据帧:

   type  status  age
5  lion    True    7
6   dog    True    5

最有效的方法是什么?

【问题讨论】:

    标签: python pandas dataframe split sequence


    【解决方案1】:

    让我们做

    s = df.status.ne(df.status.shift())
    d = {x-1 : y for x , y in df.groupby(s.cumsum())}
    d[0]
    Out[66]: 
      type  status  age
    0  dog   False    4
    d[1]
    Out[67]: 
        type  status  age
    1    cat    True    6
    2  whale    True    7
    

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 2018-04-28
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 2021-08-05
      相关资源
      最近更新 更多