如何在 pandas DataFrame 的 .loc 屬性中應用切片索引器?
loc 是 pandas DataFrame 建構函式中的一個屬性,用於根據行/列標籤索引訪問 DataFrame 的元素。
.loc 屬性採用 DataFrame 行和列的標籤來訪問元素組。
.loc 屬性允許整數、整數列表、帶整數的切片物件以及布林陣列等作為輸入。如果 DataFrame 中找不到指定的標籤,則會引發 KeyError。
示例 1
在下面的示例中,我們已將切片索引器應用於 loc 屬性,以訪問第 1-3 行的值。此處包含起始值和結束值。
# importing pandas package import pandas as pd # create a Pandas DataFrame df = pd.DataFrame({'Country':['Brazil','Canada','New Zealand','Iceland', 'India', 'Sri Lanka', 'United States'], 'Capital': [ 'Belmopan','Ottawa','Wellington','Reykjavik', 'New Delhi','Colombo', 'Washington D.C']}) print("DataFrame:") print(df) # Access the elements using slicing indexer result = df.loc[1:3] print("Output:") print(result)
輸出
輸出如下所示:
DataFrame: Country Capital 0 Brazil Belmopan 1 Canada Ottawa 2 New Zealand Wellington 3 Iceland Reykjavik 4 India New Delhi 5 Sri Lanka Colombo 6 United States Washington D.C Output: Country Capital 1 Canada Ottawa 2 New Zealand Wellington 3 Iceland Reykjavik
loc 屬性成功訪問了 3 行 (1-3) 的元素。
示例 2
現在,我們可以應用切片索引器來選擇多行標籤和列中的單個標籤。
# importing pandas package import pandas as pd # create a Pandas DataFrame df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'], index = ['r1','r2','r3','r4']) print("DataFrame:") print(df) # Access the elements using slicing indexer result = df.loc['r1':'r3','col1'] print("Output:") print(result)
輸出
輸出如下所示:
DataFrame: col1 col2 r1 a b r2 c d r3 e f r4 g h Output: r1 a r2 c r3 e Name: col1, dtype: object
我們可以注意到,切片的起始和結束位置都包含在選擇行標籤中。
廣告