大熊貓是否有機會通過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
添加回答
舉報
0/150
提交
取消