萧十郎
Idea是通过MultiIndex.from_product和DataFrame.reindex在s中创建的,因此可以相互创建多个:MultiIndexDataFramedf1 = df[['A','B','C']]df2 = pd.get_dummies(df['Month'])mux = pd.MultiIndex.from_product([df1.columns, df2.columns])df2 = df2.reindex(mux, axis=1, level=1)df1 = df1.reindex(mux, axis=1, level=0)df = df1 * df2最后一个用于正确排序,最后一个使用 s 平展数据列:CategoricalIndexf-stringmonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]df.columns = pd.MultiIndex.from_arrays([ df.columns.get_level_values(0), pd.CategoricalIndex(df.columns.get_level_values(1),categories=months,ordered=True),])df = df.sort_index(axis=1)df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')print (df) A_Jan A_Feb B_Jan B_Feb C_Jan C_Feb0 1 0 3 0 5 01 0 1 0 2 0 3