利用unstack()函数将多层索引的数据重新排列
发布时间:2024-01-09 17:10:08
unstack()函数是Pandas库中的一个用于数据重排的函数。它可将多层索引的数据重新排列,将数据从多层次的列索引转换为单层次的列索引。
下面是一个使用unstack()函数的示例:
假设我们有一个包含多层次索引的数据框,表示了各个城市不同月份的销售额和利润率,如下所示:
import pandas as pd
data = {
('City', 'Month'): ['New York', 'New York', 'Los Angeles', 'Los Angeles'],
('Sales', 'Month 1'): [10000, 20000, 15000, 25000],
('Sales', 'Month 2'): [12000, 23000, 16000, 26000],
('Profit', 'Month 1'): [2000, 4000, 3000, 5000],
('Profit', 'Month 2'): [2200, 4300, 3200, 5200]
}
df = pd.DataFrame(data)
df.columns = pd.MultiIndex.from_tuples(df.columns)
print(df)
输出结果如下:
City Sales Profit
Month Month 1 Month 2 Month 1 Month 2
0 New York 10000 12000 2000 2200
1 New York 20000 23000 4000 4300
2 Los Angeles 30000 32000 6000 6400
3 Los Angeles 40000 43000 8000 8600
这个数据框中的列索引是两层的, 层是"City"和"Month",第二层是"Sales"和"Profit"。我们可以使用unstack()函数将第二层索引"Sales"和"Profit"转换为 层索引的列,代码如下:
df_unstacked = df.unstack(level=1) print(df_unstacked)
输出结果如下:
City New York Los Angeles
Month 1 Month 2 Month 1 Month 2
Sales 10000 12000 30000 40000
Profit 2000 2200 6000 8000
Sales 20000 23000 32000 43000
Profit 4000 4300 6400 8600
通过unstack()函数的level参数,我们指定了要转换的索引级别。在本例中,我们指定了level=1,即将 层索引"Sales"和"Profit"转换为列索引的 层。
这样,我们就将多层次的列索引转换为了单层次的列索引,便于数据的查看和分析。
