亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python2.7 - Pandas 數據框按兩個標準分組

Python2.7 - Pandas 數據框按兩個標準分組

回首憶惘然 2021-12-29 10:56:19
假設我有一個 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]}


查看完整回答
反對 回復 2021-12-29
  • 1 回答
  • 0 關注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號