Pandas2.2 Series
Computations descriptive stats
方法 | 描述 |
---|---|
Series.argsort([axis, kind, order, stable]) | 用于返回 Series 中元素排序后的索引位置的方法 |
Series.argmin([axis, skipna]) | 用于返回 Series 中最小值索引位置的方法 |
Series.argmax([axis, skipna]) | 用于返回 Series 中最大值索引位置的方法 |
Series.reorder_levels(order) | 用于重新排列 Series 中多層索引(MultiIndex)層級順序的方法 |
Series.sort_values(*[, axis, ascending, …]) | 用于對 Series 中的值進行排序的方法 |
Series.sort_index(*[, axis, level, …]) | 用于根據索引對 Series 進行排序 |
Series.swaplevel([i, j, copy]) | 用于交換 MultiIndex 中的兩個級別 |
Series.unstack([level, fill_value, sort]) | 用于將 MultiIndex 中的一個或多個級別“旋轉”為列 |
pandas.Series.unstack
pandas.Series.unstack
方法用于將 MultiIndex
中的一個或多個級別“旋轉”為列,從而將長格式數據轉換為寬格式數據。這對于數據分析和可視化非常有用,可以更方便地查看和操作多級索引的數據。
參數說明
- level:整數、字符串或列表,默認為 -1(即最內層)。指定要旋轉的級別,可以是級別的位置(從 0 開始)或級別的名稱。如果傳遞一個列表,則會旋轉多個級別。
- fill_value:標量值,默認為 None。用于填充因旋轉而產生的缺失值。如果未指定,則缺失值將被設置為 NaN。
- sort:布爾值,默認為 False。如果為 True,則在返回結果之前對行索引進行排序。
示例及結果
import pandas as pd# 創建一個帶有 MultiIndex 的 Series
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
s = pd.Series(range(8), index=index)print("原始 Series:")
print(s)# 使用 unstack 將 'second' 級別旋轉為列
unstacked_s = s.unstack(level='second', fill_value=0)print("\n旋轉后的 DataFrame:")
print(unstacked_s)
輸出結果
原始 Series:
first second
bar one 0two 1
baz one 2two 3
foo one 4two 5
qux one 6two 7
dtype: int64旋轉后的 DataFrame:
second one two
first
bar 0 1
baz 2 3
foo 4 5
qux 6 7
通過上述代碼和輸出結果可以看到,unstack
方法將 MultiIndex
中的 second
級別旋轉為列,并且可以通過設置不同的參數來控制旋轉的級別、缺失值的填充以及是否對行索引進行排序。
注意事項
- 如果旋轉后產生了缺失值,可以通過
fill_value
參數指定填充值。 - 如果
MultiIndex
中有重復的組合鍵,在旋轉時可能會導致錯誤或不明確的結果。確保數據中沒有重復的組合鍵。 unstack
操作的逆操作是stack
,可以將寬格式數據轉換回長格式數據。
多級別旋轉示例
如果你想旋轉多個級別,可以傳遞一個包含級別名稱或位置的列表:
# 創建一個帶有三層 MultiIndex 的 Series
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second', 'third'])
s = pd.Series(range(8), index=index)print("原始 Series:")
print(s)# 使用 unstack 將 'second' 和 'third' 級別旋轉為列
unstacked_s_multi = s.unstack(['second', 'third'], fill_value=0)print("\n旋轉多個級別的 DataFrame:")
print(unstacked_s_multi)
輸出結果
原始 Series:
first second third
bar one a 0two b 1
baz one c 2two d 3
foo one e 4two f 5
qux one g 6two h 7
dtype: int64旋轉多個級別的 DataFrame:
second one two one two one two one two
third a b c d e f g h
first
bar 0 1 0 0 0 0 0 0
baz 0 0 2 3 0 0 0 0
foo 0 0 0 0 4 5 0 0
qux 0 0 0 0 0 0 6 7
在這個例子中,unstack
方法將 second
和 third
兩個級別同時旋轉為列,生成了一個更寬的 DataFrame。