0
如何計算(例如)多索引DataFrame級別= 1的和,並將結果存儲在新的DataFrame中,如從this_to_that獲得。對特定MultiIndex DataFrame級別函數調用的DataFrame
數據
T = ['t1','t2']
S = ['S1','S2']
K = ['earnings','costs']
multi_index = pd.MultiIndex.from_product([T,S])
input_df = pd.DataFrame(index = multi_index, columns = K)
input_df['earnings'] = (150.0,25.0,80.0,40.0)
input_df['costs'] = (150.0,12.5,36.36,22.72)
我煩瑣方式
dc = dict()
for t in T:
dc[t] = input_df.xs(t, level = 0, axis = 0).apply(sum, axis = 0)
dc_to_df = pd.concat(dc)
dc_to_df = pd.DataFrame(dc_to_df)
dc_to_df = dc_to_df.unstack(level=1)
dc_to_df.columns = dc_to_df.columns.droplevel(0)
desired_df = dc_to_df
有一個更好的選擇:'input_df.sum(level = 0)';-) – MaxU