Pandas: change multiple level column name to one level

I have a dataframe with two-level column names as: ID Value A B —————- 1 6 2 5 3 4 4 3 5 2 6 1 I want to change the column head with: column_mapping = { (‘ID’, ‘A’) : ‘ID:A’, (‘Value’, ‘B’): ‘Value:B’ } I tried rename: df.rename(columns=column_mapping, inplace=True) which does not work. Any… Read More Pandas: change multiple level column name to one level

How to add dfs with different number of column axis levels, but sharing same axis names?

I have two multi-level column dataframes: data = { ‘A’: { ‘X’: {‘Value1’: 2, ‘Value2’: 1}, ‘Y’: {‘Value1’: 2, ‘Value2’: 3} }, ‘B’: { ‘X’: {‘Value1’: 10, ‘Value2’: 11}, ‘Y’: {‘Value1’: 10, ‘Value2’: 11} } } df = pd.DataFrame(data) Which looks like this… Group A B Subgroup X Y X Y Metric Value1 Value2 Value1… Read More How to add dfs with different number of column axis levels, but sharing same axis names?

Pivoting first level of a multilevel index to be the first level of a multilevel column

I have a multilevel index dataframe like this: indx = [(‘location’, ‘a’), (‘location’, ‘b’), (‘location’, ‘c’), (‘location2’, ‘a’), (‘location2’, ‘b’), (‘location2’, ‘c’)] indx = pd.MultiIndex.from_tuples(indx) col = [‘S1′,’S2′,’S3’] df = pd.DataFrame(np.random.randn(6, 3), index=indx, columns=col) df S1 S2 S3 location a -0.453549 -0.079797 0.581657 b -0.458573 -0.732625 -2.277674 c 0.874403 0.459590 -1.220271 location2 a -1.418821 0.847556… Read More Pivoting first level of a multilevel index to be the first level of a multilevel column