假设我有一个 panadas DataFrame:import pandas as pddf = 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按连续索引(按 Pandas DataFrame 中的连续索引分组)对该框架进行分组,然后对其进行分组。所需的输出将是这样的分组:因此,行按行分组,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 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
你做错了。当您执行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]}
添加回答
举报
0/150
提交
取消