Python2.7-熊猫数据框按两个条件分组

时间:2019-04-04 15:59:21

标签: python python-2.7 pandas-groupby

让我们说我有一个panadas DataFrame:

import pandas as pd

df = pd.DataFrame(columns=['name','time'])
df = df.append({'name':'Waren', 'time': '20:15'}, ignore_index=True)
df = df.append({'name':'Waren', 'time': '20:12'}, ignore_index=True)
df = df.append({'name':'Waren', 'time': '20:11'}, ignore_index=True)
df = df.append({'name':'Waren', 'time': '01:29'}, ignore_index=True)
df = df.append({'name':'Waren', 'time': '02:15'}, ignore_index=True)
df = df.append({'name':'Waren', 'time': '02:16'}, ignore_index=True)

df = df.append({'name':'Kim', 'time': '20:11'}, ignore_index=True)
df = df.append({'name':'Kim', 'time': '01:29'}, ignore_index=True)
df = df.append({'name':'Kim', 'time': '02:15'}, ignore_index=True)
df = df.append({'name':'Kim', 'time': '01:49'}, ignore_index=True)
df = df.append({'name':'Kim', 'time': '01:49'}, ignore_index=True)
df = df.append({'name':'Kim', 'time': '02:15'}, ignore_index=True)
df = df.append({'name':'Mary', 'time': '22:15'}, ignore_index=True)
df = df.drop(df.index[2])
df = df.drop(df.index[7])

我想按name将此帧分组,然后按连续索引(Group by continuous indexes in Pandas DataFrame)分组。

所需的输出将是这样的分组:

Desired Output

因此,行按name分组,并且对于该行,此连续增加的索引仅采用第一个和最后一个元素。

我这样尝试过: df.groupby(['name']).groupby(df.index.to_series().diff().ne(1).cumsum()).group 这只会引发错误: AttributeError: Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects, try using the 'apply' method

欢迎任何帮助!

1 个答案:

答案 0 :(得分:1)

您做错了。当您执行 df.groupby(['name'])时,它将返回不可调用的属性 groupby 。您需要将两者同时应用。


df.groupby(['name', df.index.to_series().diff().ne(1).cumsum()]).groups

Out: 
{('Kim', 2): [6, 7],
 ('Kim', 3): [9, 10, 11],
 ('Mary', 3): [12],
 ('Waren', 1): [0, 1],
 ('Waren', 2): [3, 4, 5]}
相关问题