Python Pandas 库中的 stack 和 unstack 函数是什么。
Stack和unstack函数用于重塑pandas库中的DateFrame以通过不同方式提取更多信息。
堆
Pandasstack用于堆叠从列到索引的级别。它返回一个带有多级索引的新DataFrame或Series。stack方法有2个参数,分别是level和dropna。
level参数用于从列轴堆叠到索引轴,默认值为1,我们可以给出字符串、列表和整数。以及dropna用于删除结果DataFrame/Series中具有缺失值的行。默认情况下它是True,它需要布尔数据。
让我们举一个例子,看看它是如何工作的。
示例
df = pd.read_json('E:\iris.json') #使用iris数据集创建一个DataFrame df_stacked = df.stack(0) #堆叠到第0层 print(df_stacked) # display the result
解释
使用iris数据集,我们创建了一个DataFrame,它只有一个级别为0。在下一步中,将该DataFramedf堆叠到索引级别。
输出结果
0 sepalLength 5.1 sepalWidth 3.5 petalLength 1.4 petalWidth 0.2 species setosa ... 149 sepalLength 5.9 sepalWidth 3 petalLength 5.1 petalWidth 1.8 species virginica Length: 750, dtype: object
堆叠的数据帧“df”显示在上面的输出块中,结果输出是一个具有0和12个级别的系列,系列长度为750。
取消堆叠
Unstack也类似于stack方法,它返回一个具有新级别列标签的DataFrame。它有2个参数,分别是level和fill_value。
level参数采用整数、字符串、这些列表,默认值为1(1是最后一个级别)。如果unstack产生任何缺失值,则fill_value用于填充空值。
示例
在这个例子中,我们将把上面堆叠的DataFrame应用到unstack函数中。
unstacked_df = df_stacked.unstack(level=0) print(unstacked_df)
解释
从上面的例子中取出堆叠的DataFrame。这里的级别是0。结果输出DataFrame显示在下面的块中。
输出结果
0 1 2 3 4 5 6 7 \ sepalLength 5.1 4.9 4.7 4.6 5 5.4 4.6 5 sepalWidth 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 petalLength 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 petalWidth 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 species setosa setosa setosa setosa setosa setosa setosa setosa 8 9 ... 140 141 142 143 \ sepalLength 4.4 4.9 ... 6.7 6.9 5.8 6.8 sepalWidth 2.9 3.1 ... 3.1 3.1 2.7 3.2 petalLength 1.4 1.5 ... 5.6 5.1 5.1 5.9 petalWidth 0.2 0.1 ... 2.4 2.3 1.9 2.3 species setosa setosa ... virginica virginica virginica virginica 144 145 146 147 148 149 sepalLength 6.7 6.7 6.3 6.5 6.2 5.9 sepalWidth 3.3 3 2.5 3 3.4 3 petalLength 5.7 5.2 5 5.2 5.4 5.1 petalWidth 2.5 2.3 1.9 2 2.3 1.8 species virginica virginica virginica virginica virginica virginica [5 rows x 150 columns]
级别为0的未堆叠DataFrame有5行和150列。使用这些stack和unstack函数,我们可以轻松地从DataFrame中提取数据,并且可以轻松地重塑多级DataFrame。