如何使用 .loc 屬性訪問 Pandas DataFrame 元素?
“.loc” 是 pandas.DataFrame 的一個屬性。它用於根據行/列標籤索引從 DataFrame 中訪問元素。它的工作原理類似於 pandas.DataFrame 的“at”屬性,但區別在於,“at”屬性僅用於訪問單個元素,而“loc”屬性可以訪問一組元素。
“.loc” 屬性允許使用整數、整數列表、帶整數的切片物件、布林陣列等作為輸入。如果 DataFrame 中未找到指定的標籤,它將引發 KeyError。
示例 1
在以下示例中,我們使用包含鍵值對的 Python 字典建立了一個 Pandas DataFrame“df”。此處,索引標籤是透過使用 index 引數指定的。
# importing pandas package import pandas as pd # create a Pandas DataFrame df = pd.DataFrame({'B':['black','Blue'], 'W':['white','wine'],'R':['red', 'rose dust'],'G':['green','gray']}, index=['row1','row2']) print("DataFrame:") print(df) # get the elements by labels result = df.loc['row2', 'W'] print("Output:") print(result)
輸出
輸出如下所示:
DataFrame: B W R G row1 black white red green row2 Blue wine rose dust gray Output: wine
我們已成功透過向 loc 屬性指定行/列標籤從 DataFrame“df”中訪問單個元素。
示例 2
在這裡,我們將透過向“loc”屬性提供標籤列表來訪問 Pandas.DataFrame 中的一組元素。
# importing pandas package import pandas as pd # create a Pandas DataFrame df = pd.DataFrame({'B':['black','Blue'], 'W':['white','wine'],'R':['red', 'rose dust'],'G':['green','gray']}, index=['row1','row2']) print("DataFrame:") print(df) # set the elements by labels result = df.loc[['row1','row2']] print("Output:") print(result)
輸出
輸出如下所示:
DataFrame: B W R G row1 black white red green row2 Blue wine rose dust gray Output: B W R G row1 black white red green row2 Blue wine rose dust gray
loc 屬性成功地使用“loc”屬性從 Pandas DataFrame 中訪問了兩行(row1 和 row2)的元素。結果,它返回一個新的 DataFrame,如上面的輸出塊中所示。
廣告