如何计算(例如)每个列的多索引DataFrame级别= 1的总和,并存储新的DataFrame,例如从this_to_that获取。
数据
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
答案 0 :(得分:1)
这是你要找的吗?
input_df
earnings costs
t1 S1 150.0 150.00
S2 25.0 12.50
t2 S1 80.0 36.36
S2 40.0 22.72
input_df.groupby(level=0).sum()
earnings costs
t1 175.0 162.50
t2 120.0 59.08
您可以将上述输出分配给新的数据帧。
编辑:查看您的输出后,您实际上正在level=0
进行分组。