pandas.series.index 屬性的作用是什麼?


Series 是 pandas 的一種資料結構,用於儲存單維的帶標籤資料,標籤可以是文字資料、整數或時間序列等。透過這些標籤,我們可以訪問 Series 中的元素並進行資料操作。

在 pandas.Series 中,標籤被稱為索引。如果要單獨獲取索引標籤,可以使用 pandas.Series 的“index”屬性。

示例 1

import pandas as pd

# creating a series
s = pd.Series([100,110,120,130,140])
print(s)

# Getting index data
index = s.index

print('Output: ')

# displaying outputs
print(index)

解釋

使用長度為 5 的包含整數的 Python 列表初始化 pandas Series 物件。s.index 屬性將返回基於給定 Series 物件的索引標籤列表。

輸出

0  100
1  110
2  120
3  130
4  140
dtype: int64

Output:
RangeIndex(start=0, stop=5, step=1)

在本例中,建立 Series 物件時沒有初始化索引標籤。因此,pandas.Series 建構函式將自動提供索引標籤。

index 屬性訪問自動建立的標籤(RangeIndex 值),這些值顯示在上面的輸出塊中。

示例 2

import pandas as pd

Countrys = ['Iceland', 'India', 'United States']
Capitals = [ 'Reykjavik', 'New Delhi', 'Washington D.C']

# create series
s = pd.Series(Capitals, index=Countrys)

# display Series
print(s)

# Getting index data
index = s.index

print('Output: ')
# displaying outputs
print(index)

解釋

在下面的示例中,我們使用兩個 Python 列表物件建立了一個 pandas Series,每個列表都包含國家的名稱(字串)和首都的名稱。

輸出

Iceland              Reykjavik
India                New Delhi
United States   Washington D.C
dtype: object
Output:
Index(['Iceland', 'India', 'United States'], dtype='object')

s.index 屬性將返回給定 Series 物件“s”的標籤列表,這些索引標籤的資料型別為“object”型別。

更新於:2022年3月9日

瀏覽量:373

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告