假設(shè)我有一個 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按連續(xù)索引(按 Pandas DataFrame 中的連續(xù)索引分組)對該框架進(jìn)行分組,然后對其進(jìn)行分組。所需的輸出將是這樣的分組:因此,行按行分組,name并且對于行,此連續(xù)增加的索引僅采用第一個和最后一個元素。我這樣試過: df.groupby(['name']).groupby(df.index.to_series().diff().ne(1).cumsum()).group 這只會引發(fā)錯誤: AttributeError: Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects, try using the 'apply' method歡迎任何幫助!
1 回答

慕妹3146593
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個贊
你做錯了。當(dāng)您執(zhí)行df.groupby(['name']) 時(shí),它會返回不可調(diào)用的屬性groupby。你需要同時(shí)應(yīng)用它。
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]}
添加回答
舉報(bào)
0/150
提交
取消