慕无忌1623718
在熊猫中使用groupby时,将根据列数据对数据进行分组。但是,您有成行的组。您所需要做的就是在分组之前和之后对df进行转置。这是您需要的代码:首先,让我们像您一样创建df:import pandas as pdindex = pd.MultiIndex.from_tuples([(2016, 3, 'Sep', 'A'), (2016, 3, 'Sep', 'B'), (2016, 3, 'Sep', 'C'), (2016, 4, 'Oct', 'A'), (2016, 4, 'Oct', 'B'), (2016, 4, 'Oct', 'C'), (2016, 4, 'Nov', 'A'), (2016, 4, 'Nov', 'B'), (2016, 4, 'Nov', 'C'), (2017, 1, 'Jan', 'A'), (2017, 1, 'Jan', 'B'), (2017, 1, 'Jan', 'C'), (2017, 1, 'Feb', 'A'), (2017, 1, 'Feb', 'B'), (2017, 1, 'Feb', 'C'), ], names=['Year', 'Quarter', 'Month', 'Group'])raw_df = pd.Series(range(15), index=index)df = raw_df.unstack([0,1,2])print(df)输出:Year 2016 2017 Quarter 3 4 1 Month Sep Oct Nov Jan FebGroup A 0 3 6 9 12B 1 4 7 10 13C 2 5 8 11 14看起来与您的示例完全相同。现在您只需要一行代码:new_df = df.transpose().groupby(['Year', 'Quarter']).sum().transpose()print(new_df)这是您的输出:Year 2016 2017Quarter 3 4 1Group A 0 9 21B 1 11 23C 2 13 25祝你好运!
慕的地8271018
df.sum(level=['Year', 'Quater'], axis=1)重现完整示例:import pandas as pdtuples = [(2016, 3, 'Sep'), (2016, 4, 'Oct'), (2016, 4, 'Nov'), (2016, 4, 'Dec'), (2017, 1, 'Jan'), (2017, 1, 'Feb'), (2017, 1, 'Mar'), (2017, 2, 'Apr'), (2017, 2, 'May'), (2017, 2, 'Jun')]index = pd.MultiIndex.from_tuples(tuples, names=['Year', 'Quater', 'Month'])df = pd.DataFrame([(0.16, 0.88, 0.79), (0.95, 0.67, 0.56), (0.92, 0.07, 0.13), (0.45, 0.70, 0.19), (0.30, 0.74, 0.94), (0.35, 0.33, 0.23), (0.95, 0.77, 0.72), (0.88, 0.21, 0.62), (0.18, 0.81, 0.66), (0.10, 0.85, 0.93)], index=index, columns=["A", "B", "C"])df = df.Tprint(df.sum(level=['Year', 'Quater'], axis=1))