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

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

熊貓groupby和Multiindex

熊貓groupby和Multiindex

郎朗坤 2021-03-14 05:15:12
大熊貓是否有機會通過MultiIndex對數據進行分組?我的意思是,不僅要傳遞鍵給groupby函數,還要傳遞鍵和值來預定義數據幀列?a = np.array(['foo', 'foo', 'foo', 'bar', 'bar', 'foo', 'foo'], dtype=object)b = np.array(['one', 'one', 'two', 'one', 'two', 'two', 'two'], dtype=object)c = np.array(['dull', 'shiny', 'dull', 'dull', 'dull', 'shiny', 'shiny'], dtype=object)df = pd.DataFrame([a, b, c]).Tdf.columns = ['a', 'b', 'c']df.groupby(['a', 'b', 'c']).apply(len)a    b    c    bar  one  dull     1     two  dull     1foo  one  dull     1          shiny    1     two  dull     1          shiny    2但是我真正想要的是以下內容:mi = pd.MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], ['dull', 'shiny']],                   labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]])#pseudocodedf.groupby(['a', 'b', 'c'], multi_index = mi).apply(len)a    b    c    bar  one  dull     1          shiny    0     two  dull     1          shiny    0foo  one  dull     1          shiny    1     two  dull     1          shiny    2我看到的方式是在groupby對象上創建其他包裝。還是該功能與熊貓哲學相得益彰,可以包含在熊貓庫中?
查看完整描述

1 回答

?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

只需重新索引和fillna!


In [14]: df.groupby(['a', 'b', 'c']).size().reindex(index=mi).fillna(0)

Out[14]: 

foo  one  dull     1

          shiny    1

     two  dull     1

          shiny    2

bar  one  dull     1

          shiny    0

     two  dull     1

          shiny    0

dtype: float64


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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