【问题标题】:Splitting time series data into groups based on a changes in state on a column in a python pandas dataframe根据 python pandas 数据框中列的状态变化将时间序列数据分组
【发布时间】:2014-01-16 09:36:13
【问题描述】:

我需要在 pandas 数据框中对一些数据进行分组,但标准的分组方法并不能完全满足我的需要。它必须分组,以便“loc”中的每个更改和/或“name”中的每个更改都被视为一个单独的组。

示例;

x = pd.DataFrame([['john','abc',1],['john','abc',2],['john','abc',3],['john','xyz',4],['john','xyz',5],['john','abc',6],['john','abc',7],['matt','abc',8]])
x.columns = ['name','loc','time']

name    loc  time
john    abc  1
john    abc  2
john    abc  3
john    xyz  4
john    xyz  5
john    abc  6
john    abc  7
matt    abc  8

我需要对这些值进行分组,以便生成的数据是

name    loc  first last
john    abc  1     3
john    xyz  4     5
john    abc  6     7
matt    abc  8     8

默认的分组功能(正确)对所有 loc 和 name 值进行分组,所以我们只剩下 3 个组(john / abc 是 1 个组)。有人知道如何强制分组按我的要求分组吗?

我能够使用 for 循环 (iterrows) 生成所需的表,但如果有一个不错的 pandas pythonic 方式来做同样的事情,我很想知道。

提前谢谢你。

马特

【问题讨论】:

  • 只是为了确定,您是否想要结果中的倒数第二行,第二行 ('john', 'abc')。我知道Github上有一个关于连续groupbys的问题,我看看能不能找到。

标签: python pandas


【解决方案1】:

这对于groupby 来说并不是真正的工作,因为行的顺序很重要。而是使用shift 比较连续的行。

In [37]: cols = ['name', 'loc']

In [38]: change = (x[cols] != x[cols].shift(-1)).any(1).shift(1).fillna(True)

In [39]: groups = x[change]

In [40]: groups.columns = ['name', 'loc', 'first']

In [41]: groups['last'] = (groups['first'].shift(-1) - 1).fillna(len(x))

In [42]: groups
Out[42]:
   name  loc  first  last
0  john  abc      1     3
3  john  xyz      4     5
5  john  abc      6     7
7  matt  abc      8     8

[4 rows x 4 columns]

【讨论】:

    【解决方案2】:

    您可以使用groupby中的函数:

    x = pd.DataFrame([['john','abc',1],['john','abc',2],['john','abc',3],['john','xyz',4],['john','xyz',5],['john','abc',6],['john','abc',7],['matt','abc',8]])
    x.columns = ['name','loc','time']
    
    last_group = None
    c =0
    def f(y):
        global c,last_group
        g = x.irow(y)['name'],x.irow(y)['loc']
        if last_group != g:
            c += 1
            last_group = g
        return c
    
    print x.groupby(f).head()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 2021-08-05
      • 2021-02-11
      • 1970-01-01
      • 2020-12-21
      • 2021-01-21
      • 2015-09-26
      • 1970-01-01
      相关资源
      最近更新 更多