如何調整 Pandas Series 的形狀?
我們可以使用轉置、reshape 方法和 melt 函式等方法來調整 Pandas 系列。Pandas 系列是一個一維標籤陣列,它可以容納任何型別的陣列(整數、浮點數、字串等)。它類似於 NumPy 陣列,但每個元素都關聯了一個索引,該索引可以用來訪問各個值。重塑是指改變 Pandas 系列的形狀或結構,以便以各種方式使用資料。
演算法
使用不同方法重塑 Pandas 系列的一般演算法如下所示 −
用一些資料建立一個 Pandas 系列。
使用 reshape() 方法將系列的形狀更改為所需的形狀。
使用 stack() 方法將系列從寬格式轉換為長格式(如果需要)。
使用 melt() 方法將系列從寬格式轉換為長格式(如果需要)。
使用 unstack() 方法將系列從長格式轉換為寬格式(如果需要)。
使用 pivot() 方法將系列從長格式轉換為寬格式(如果需要)。
如有需要,可以使用 T 屬性來轉置 series。
方法 1:使用 Transpose 屬性
transpose 函式 (T) 可用於切換 series 的行和列。當我們需要以不同方式視覺化資料時,此功能非常有用。
語法
在此,T 是一種屬性,而不是方法,因此在使用它時不需要使用圓括號。此外,由於它是一種屬性,而不是方法,因此不能接受任何引數。T 屬性會返回一個新 DataFrame,其行和列已互換。
示例
在下例中,我們建立了一個 pandas series,然後使用 transpose 函式轉置 pandas series,最後輸出轉置後的 series。
import pandas as pd # Create a Series s = pd.Series([1, 2, 3, 4]) # Transpose the Series s_transposed = s.T # Print the transposed Series print(s_transposed)
輸出
0 1 1 2 2 3 3 4 dtype: int64
方法 2:使用 reshape 方法。
可以使用 reshape 方法來更改 series 的形狀。此方法要求新形狀與原始形狀相容。
語法
DataFrame.reshape(shape[, order])
在此,shape 引數指定陣列的新維度,而可選的 order 引數指定陣列元素的排列順序。
示例
在下例中,使用 values.reshape() 方法重塑 pandas series。首先建立包含 1 到 9 的值的 series。然後,使用 values.reshape(3,3) 將 series 重塑為 3x3 大小的矩陣。
import pandas as pd import numpy as np # Create a Series s = pd.Series(np.arange(1, 10)) # Reshape the Series s_reshaped = s.values.reshape((3, 3)) # Print the reshaped Series print(s_reshaped)
輸出
[[1 2 3] [4 5 6] [7 8 9]]
方法 3:使用 Melt 函式
可以使用 melt 函式解除 series 的透視。此函式會為原始 series 中的每個唯一值建立一個新資料幀,併為每個唯一值組合建立一個行。
語法
DataFrame.melt([id_vars, value_vars, ...], ...)
在此, id_vars 引數指定要用作識別符號變數的列,value_vars 引數指定要取消透視的列,還可以使用其他引數自定義輸出。
示例
在下例中,我們首先使用 reset_index 方法將 Series s 轉換為 DataFrame,該方法會建立一個新的 'index' 列,其中包含原始 Series 索引值。然後我們在此 DataFrame 上使用 melt 函式,並將 'index' 指定為 id_vars 引數,並指定 '0'(包含原始 Series 值的列的名稱)作為 value_vars 引數。
import pandas as pd
# Create a Series
s = pd.Series({'A': 1, 'B': 2, 'C': 3})
# Convert the Series to a DataFrame using reset_index()
df = s.reset_index()
# Melt the DataFrame
df_melted = pd.melt(df, id_vars='index', value_vars='0')
# Print the melted DataFrame
print(df_melted)
輸出
index variable value 0 A 0 1 1 B 0 2 2 C 0 3
方法 4:使用 unstack() 方法
Pandas 中的 unstack() 方法用於將多級索引 Series 或 DataFrame 重塑為寬格式。此方法本質上是將多級索引的最內層級旋轉為新 DataFrame 的列。unstack() 方法是 stack() 方法的逆方法。
語法
Series.unstack(level=-1, fill_value=None)
在此,level 引數指定要取消堆疊的索引層,而 fill_value 引數指定要填充缺失值的值。
示例
在下例中,我們首先建立一個具有兩個索引層(“First”和“Second”)的多級索引 DataFrame df。然後我們對 DataFrame 使用
unstack() 方法,將最內層“Second”旋轉為新 DataFrame 的列。生成的 DataFrame df_unstacked 具有列“A”和“B”,原始索引層“First”和“Second”保留為行標籤。
import pandas as pd
# Create a multi-level index DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=pd.MultiIndex.from_tuples([('X', 'a'), ('X', 'b'), ('Y', 'c')], names=['First', 'Second']))
# Unstack the DataFrame
df_unstacked = df.unstack()
# Print the unstacked DataFrame
print(df_unstacked)
輸出
A B Second a b c a b c First X 1.0 2.0 NaN 4.0 5.0 NaN Y NaN NaN 3.0 NaN NaN 6.0
方法 5:使用 pivot() 方法
Pandas 中的 pivot() 方法用於將 DataFrame 從長格式重塑為寬格式。此方法採用三個引數:index、columns 和 values。index 引數指定要用作結果 DataFrame 的行索引的列,columns 引數指定要用作結果 DataFrame 的列索引的列,values 引數指定要用作結果 DataFrame 的值。
語法
DataFrame.pivot([index, columns, values])
在此,index 引數指定要作為行索引的列,columns 引數指定要作為列索引的列,values 引數指定要作為資料值使用的列。
示例
在下例中,我們首先使用三列“Year”、“Quarter”和“Sales”建立一個長格式的 DataFrame df。然後,我們在 DataFrame 上使用 pivot() 方法,指定“Year”為 index 引數,“Quarter”為 columns 引數,“Sales”為 values 引數。結果 DataFrame df_pivoted 有兩列“Q1”和“Q2”,其中“Year”為行索引。
import pandas as pd
# Create a long format DataFrame
df = pd.DataFrame({'Year': [2019, 2019, 2020, 2020], 'Quarter': ['Q1', 'Q2', 'Q1', 'Q2'], 'Sales': [100, 200, 150, 250]})
# Pivot the DataFrame
df_pivoted = df.pivot(index='Year', columns='Quarter', values='Sales')
# Print the pivoted DataFrame
print(df_pivoted)
輸出
Quarter Q1 Q2 Year 2019 100 200 2020 150 250
結論
在本文中,我們討論瞭如何使用 transpose、reshape 和 melt 函式等方法重塑 Pandas 系列。我們可以重塑 Pandas 系列,將資料轉換為不同的格式,用於視覺化、聚合或分組資料,以及將多個數據系列合併和組合到資料幀中。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP