import pandas as pdInflation_dict_country1= { "Inflation":[3, 3.2, 3.6, 3.9], "Year":[2015, 2016, 2017, 2018] , "Country":["Country 1"]*4 }Inflation_dict_country2 = { "Inflation":[2.8, 2.7, 2.8, 3.2], "Year":[2016, 2017, 2018, 2019], "Country":["Country 2"]*4 }Inflation_df_country1 = pd.DataFrame(Inflation_dict_country1)Inflation_df_country1.set_index(['Year', 'Country'], inplace=True)Inflation_df_country2 = pd.DataFrame(Inflation_dict_country2)Inflation_df_country2.set_index(['Year', 'Country'], inplace=True)Inflation_df = pd.concat([Inflation_df_country1, Inflation_df_country2])
如果要把两个级别的行索引重建成两个级别的列索引,可以使用 DataFrame.stack() 函数,如下所示:
Inflation_df = Inflation_df.stack()
这样,就可以把原来的两个级别的行索引重建成两个级别的列索引。如果要把列索引重建成行索引,可以使用 DataFrame.unstack() 函数。
此外,还可以使用 DataFrame.reset_index() 函数来重置索引,将索引转换为普通列,如下所示:
Inflation_df = Inflation_df.reset_index()
这样,就可以把原来的索引转换为普通的列,并且可以自定义列的名称。例如,可以使用 columns 参数来指定列的名称,如下所示:
Inflation_df = Inflation_df.reset_index(columns=['Year', 'Country', 'Level1', 'Inflation'])
在这个代码中,我们指定了四列的名称,分别是 Year、Country、Level1 和 Inflation。其中,Level1 是新生成的列,它用于存储原来的第一级别索引的值。
总之,如果要重建索引,可以使用 stack() 和 unstack() 函数来把行索引重建成列索引,或者使用 reset_index() 函数来把索引重置为普通列。