如何使用 .loc 屬性訪問 pandas Series 元素?


“.loc”是 pandas.Series 物件的一個屬性,用於基於標籤索引訪問系列中的元素。它與 pandas.Series 的“at”屬性類似,但區別在於,“at”屬性僅訪問單個元素,而“loc”屬性可以使用標籤訪問一組元素。

“loc”屬性基於標籤訪問標籤,並且它也支援使用標籤的切片物件。

示例 1

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)

print("Output: ")
print(series.loc['B'])

解釋

在下面的示例中,我們使用包含鍵值對的 Python 字典建立了一個 pandas series 物件“series”。這裡的索引標籤是使用字典中的鍵建立的。

輸出

B  black
W  white
R    red
Bl  blue
G  green
dtype: object

Output:
black

我們已成功地使用標籤“B”透過“loc”屬性訪問了 pandas.Series 物件“series”中的單個元素。“B”標籤被賦予了 loc 屬性。

示例 2

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)

print("Output: ")
print(series.loc['B':'G'])

解釋

在下面的示例中,我們將透過向“loc”屬性提供切片物件來訪問 pandas.Series 物件中的一組元素。

輸出

B  black
W  white
R    red
Bl  blue
G  green
dtype: object

Output:
B  black
W  white
R    red
Bl  blue
G  green
dtype: object

我們已經使用“loc”屬性訪問了一組 pandas.Series 元素。我們得到另一個系列物件作為結果,如上面的輸出塊中所示。如果系列物件中不存在提供的標籤,它將引發 KeyError。

更新於:2022年3月9日

瀏覽量:536

啟動您的職業生涯

完成課程獲得認證

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