如何在 Pandas Series 中展開(explode)一行?


如果 Series 物件中的一些元素包含列表,則可以將這些列表元素展開到 Series 物件的多行中。展開就是將列表轉換成多行。

因此,可以使用 Pandas Series 的 `explode()` 方法輕鬆完成此轉換。此方法用於將 Series 物件的列表型元素轉換為行,並且這些行的索引將被複制。

此方法唯一的引數是 `ignore_index`,它接受布林值,預設為 False,True 表示生成的索引將從 0 到 n-1 標記。

示例 1

在下面的示例中,我們將看到 `series.explode()` 方法如何將 Series 物件的列表型元素轉換為行。

# importing pandas package
import pandas as pd

# create a nested list
L = [1, 2, [4, 8, 9, 2], [], ["a", "b", "c"]]

# Create a pandas series using the list
series = pd.Series(L)

# unnest the series using explode() method
result = series.explode()

print("Original Series:")
print(series)

print("Result:", result)

解釋

這裡我們建立了一個帶有 Python 巢狀列表的 Series 物件,然後應用了 `explode()` 方法。

輸出

輸出如下:

Original Series:
0              1
1              2
2    [4, 8, 9, 2]
3              []
4       [a, b, c]
dtype: object

Result:
0    1
1    2
2    4
2    8
2    9
2    2
3  Nan
4    a
4    b
4    c
dtype: object

在上面的輸出塊中,我們可以注意到元素 4、8、9、2 被轉換成了結果 Series 物件的新行。此外,在索引位置 3 處有一個空的列表型元素,結果行在該位置 3 將具有 np.nan。

示例 2

在下面的示例中,我們將看到 `series.explode()` 方法如何將 Series 中類似列表、元組的物件元素轉換為行。

# importing pandas package
import pandas as pd

# Create a pandas series
series = pd.Series([(0, 1, 2,), list("xyz"), (5, 6, 7)])

# unnest the series using explode() method
result = series.explode()

print("Original Series:")
print(series)

print("Result:", result)

解釋

最初,我們建立了一個包含 3 個元素(元組、列表)的 Python 列表的 Series 物件,然後應用了 `explode()` 方法。

輸出

輸出如下:

Original Series:
0    (0, 1, 2)
1    [x, y, z]
2    (5, 6, 7)
dtype: object

Result:
0    0
0    1
0    2
1    x
1    y
1    z
2    5
2    6
2    7
dtype: object

在上面的輸出塊中,我們可以注意到 Series 物件的元素已成功轉換為結果 Series 物件的新行。

更新於:2022年3月7日

1K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.