使用Pandas stack()方法堆叠单层列?
在Pandas中,我们通常会处理一些有层级结构的数据,如多层索引或多层列。当我们需要将多层列转换为单层列时,可以使用Pandas的stack()
方法。
什么是stack()方法?
stack()
方法是Pandas中的一个重要方法,它可以将DataFrame中的多层列转换为单层列。该方法的主要功能是将DataFrame从“宽格式”转换为“长格式”。这种操作对于某些数据分析和可视化操作很有用。
例如,假设我们有一个数据集包含多层列,如下所示:
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.rand(4, 2),
index=[('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd')],
columns=['col_1', 'col_2'])
df
输出结果如下:
col_1 col_2
A a 0.548814 0.715189
B b 0.602763 0.544883
C c 0.423655 0.645894
D d 0.437587 0.891773
该数据集包含多层列,我们可以使用stack()
方法将其转换为单层列:
df_stacked = df.stack()
df_stacked
输出结果如下:
A a col_1 0.548814
col_2 0.715189
B b col_1 0.602763
col_2 0.544883
C c col_1 0.423655
col_2 0.645894
D d col_1 0.437587
col_2 0.891773
dtype: float64
使用stack()方法的参数
stack()
方法有一些参数可以调整转换过程的行为。其中最重要的参数是level
,它可以控制哪些层级会被转换为单层列。默认情况下,该方法会将最内层(即最后一个)的列转换为单层列。可以使用level
参数指定转换哪个层级。
以前面的数据集为例,如果我们只想将第一层列转换为单层列,可以通过以下方式实现:
df_stacked = df.stack(level=0)
df_stacked
输出结果如下:
a col_1 0.548814
col_2 0.715189
b col_1 0.602763
col_2 0.544883
c col_1 0.423655
col_2 0.645894
d col_1 0.437587
col_2 0.891773
dtype: float64
我们也可以通过指定level
参数来选择性地将多个列转换为单层列:
df_stacked = df.stack(level=[0, 1])
该方法还可以控制单层列的命名。默认情况下,单层列的层级名称将被包含在单层列的名称中。例如,在上面的示例中,单个列命名为'col_1'
,而stack()
方法的默认输出将是('A', 'a', 'col_1')
。如果要使用自定义名称替换此默认值,可以使用name
参数。
df_stacked = df.stack(level=-1, dropna=False, name="stacked")
df_stacked
输出结果如下:
A a col_1 0.548814
col_2 0.715189
B b col_1 0.602763
col_2 0.544883
C c col_1 0.423655
col_2 0.645894
D d col_1 0.437587
col_2 0.891773
Name: stacked, dtype: float64
由此可见,由stack()
方法生成的单层列已被重新命名为stacked
,并且默认情况下,层级信息已被移除,因为我们将dropna
参数设置为了False
(默认情况下为True
)。
unstack()方法:stack()方法的逆向操作
unstack()
方法是stack()
方法的逆向操作。它可以将通常为单层列的数据集转换为多层列。该方法还具有一个可选参数level
,它可以控制在哪个层级上进行不受限操作。
例如,我们可以使用之前生成的,包含单层列的数据集df_stacked
来演示unstack()
方法的使用:
df_unstacked = df_stacked.unstack()
df_unstacked
输出结果如下:
col_1 col_2
A a 0.548814 0.715189
B b 0.602763 0.544883
C c 0.423655 0.645894
D d 0.437587 0.891773
由此可见,unstack()
方法将生成一个具有两个层级的多层列数据集,其中第一层包含两个列名'col_1'
和'col_2'
,而第二层包含原始数据的前两行索引A a
和B b
。
实际案例
下面我们来看一个更实际的使用场景。假如我们手头有一份销售数据集,包含在不同年份,各个地区的产品销售额,如下:
import pandas as pd
import numpy as np
# create dataset
np.random.seed(10)
index = pd.MultiIndex.from_product([['2019', '2020'], ['North', 'South', 'East', 'West']],
names=['Year', 'Region'])
columns = pd.MultiIndex.from_product([['Product_A', 'Product_B'], ['Price', 'Quantity']],
names=['Product', 'Metric'])
data = np.random.randint(low=0, high=100, size=(8, 4))
df = pd.DataFrame(data=data, index=index, columns=columns)
df
输出结果如下:
Product Product_A Product_B
Metric Price Quantity Price Quantity
Year Region
2019 North 9 4 87 79
South 4 63 14 3
East 0 15 37 28
West 83 26 30 89
2020 North 15 11 1 95
South 76 70 88 39
East 52 76 39 92
West 14 50 68 88
我们可以使用stack()
方法将多层列转换为单层列,以便更好地展示数据:
df_stacked = df.stack(level=-1, dropna=False, name="stacked")
df_stacked
输出结果如下:
Year Region Product Metric
2019 North Product_A Price 9
Quantity 4
Product_B Price 87
Quantity 79
South Product_A Price 4
Quantity 63
Product_B Price 14
Quantity 3
East Product_A Price 0
Quantity 15
Product_B Price 37
Quantity 28
West Product_A Price 83
Quantity 26
Product_B Price 30
Quantity 89
2020 North Product_A Price 15
Quantity 11
Product_B Price 1
Quantity 95
South Product_A Price 76
Quantity 70
Product_B Price 88
Quantity 39
East Product_A Price 52
Quantity 76
Product_B Price 39
Quantity 92
West Product_A Price 14
Quantity 50
Product_B Price 68
Quantity 88
Name: stacked, dtype: int64
现在我们可以通过使用unstack()
方法将数据的多层列转换回原始格式:
df_unstacked = df_stacked.unstack()
df_unstacked
输出结果如下:
Product Product_A Product_B
Metric Price Quantity Price Quantity
Year Region
2019 East 0 15 37 28
North 9 4 87 79
South 4 63 14 3
West 83 26 30 89
2020 East 52 76 39 92
North 15 11 1 95
South 76 70 88 39
West 14 50 68 88
我们可以看到,unstack()
方法已将多层列转换回原始格式。
结论
在本文中,我们介绍了Pandas中的stack()
方法,它可以将多层列转换为单层列。我们还探讨了该方法的参数、输出格式和使用案例,并介绍了它的逆操作unstack()
方法。通过了解这些,您将能够更好地处理有结构的数据集。