如何在 Python Pandas 中使用索引標籤選擇資料子集?


簡介

Pandas 具有雙重選擇功能,可以使用索引位置或索引標籤選擇資料子集。在這篇文章中,我將向您展示如何使用索引標籤“使用索引標籤選擇資料子集”。

請記住,Python 字典和列表是內建資料結構,它們要麼使用索引標籤,要麼使用索引位置來選擇其資料。字典的鍵必須是字串、整數或元組,而列表必須使用整數(位置)或切片物件進行選擇。

Pandas 有 .loc 和 .iloc 屬性可用於以其獨特的方式執行索引操作。)。使用 .iloc 屬性,pandas 僅按位置選擇,並且與 Python 列表的工作方式類似。.loc 屬性僅按索引標籤選擇,這類似於 Python 字典的工作方式。

使用 .loc[] 使用索引標籤選擇資料子集

loc 和 iloc 屬性在 Series 和 DataFrame 上都可用

1.匯入電影資料集,並將標題作為索引。

import pandas as pd
movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv",
index_col="title",
usecols=["title","budget","vote_average","vote_count"])

我總是建議對索引進行排序,尤其是在索引由字串組成的情況下。如果您處理的是大型資料集,並且您的索引已排序,您會注意到差異。

movies.sort_index(inplace = True)
movies.head(3)


     budget vote_average vote_count
title
___________________________________
#Horror 1500000 3.3 52
(500) Days of Summer 7500000 7.2 2904
10 Cloverfield Lane 15000000 6.8 2468

我已經使用 sort_index 和“inplace = True”引數對索引進行了排序。

1.關於 loc 方法語法的一個有趣之處在於它不使用括號(),而是使用方括號[]。我認為(可能錯了)這是因為他們希望保持一致性,即您可以在 Series 上使用 [] 提取行,而在 Dataframe 上應用則會獲取列。

# extract "Spider-Man 3" ( I'm not a big fan of spidy)
movies.loc["Spider-Man 3"]


budget 258000000.0
vote_average 5.9
vote_count 3576.0
Name: Spider-Man 3, dtype: float64

1.使用切片提取多個值。我將提取我尚未觀看的電影。因為這是一個字串標籤,所以我們將獲取所有搜尋條件的資料,包括“阿凡達”。

請記住 - 如果您使用 Python 列表,則最後一個值將被排除,但由於我們正在使用字串,因此它是包含的。

movies.loc["Alien":"Avatar"]


budget vote_average vote_count
title
Alien 11000000 7.9 4470
Alien Zone 0 4.0 3
Alien: Resurrection 70000000 5.9 1365
Aliens 18500000 7.7 3220
Aliens in the Attic 45000000 5.3 244
... ... ... ...
Australia 130000000 6.3 694
Auto Focus 7000000 6.1 56
Automata 7000000 5.6 670
Autumn in New York 65000000 5.7 135
Avatar 237000000 7.2 11800

167 行 × 3 列

1.我可以獲取任何兩個或多個不彼此相鄰的隨機電影嗎?當然可以,但是您需要更加努力地傳遞您需要的電影列表。

我的意思是您需要在方括號中使用方括號。

movies.loc[["Avatar","Avengers: Age of Ultron"]]

budget vote_average vote_count
title
Avatar 237000000 7.2 11800
Avengers: Age of Ultron 280000000 7.3 6767

6.我可以更改選擇順序嗎?當然,您可以透過按順序指定您需要的標籤列表來幫助自己。

雖然指定要提取的標籤列表看起來很酷,但您知道如果拼寫錯誤會發生什麼嗎?Pandas 會為拼寫錯誤的標籤附加缺失值 (NaN)。但這些日子已經過去了,最新的更新會引發異常。

movies.loc[["Avengers: Age of Ultron","Avatar","When is Avengers next movie?"]]


---------------------------------------------------------------------------
KeyError
Traceback (most recent call last)
<ipython-input-6-ebe975264840> in <module>
----> 1 movies.loc[["Avengers: Age of Ultron","Avatar","When is Avengers next movie?"]]

~\anaconda3\lib\site-packages\pandas\core\indexing.py in
__getitem__
(self, key)
1766
1767 maybe_callable = com.apply_if_callable(
key,self.obj)
-> 1768
return self._getitem_axis(maybe_callable,axis = axis)
1769
1770 def_is_scalar_access(self,key:Tuple):
~\anaconda3\lib\site-packages\pandas\core\indexing.py
in
_getitem_axis
(self, key, axis)
1952 raiseValueError("Cannot index with multidimensional key")
1953
-> 1954 return self._getitem_iterable(key,
axis=axis)
1955
1956 # nested tuple slicing
~\anaconda3\lib\site-packages\pandas\core\indexing.py
in_getitem_iterable(self, key, axis)
1593 else:
1594 # A collection of keys
-> 1595 keyarr,indexer=self._get_listlike_indexer(key,axis,raise_missing=False)
1596 return self.obj._reindex_with_indexers(
1597 {axis:[keyarr,indexer]},copy=True,allow_dups=True
~\anaconda3\lib\site-packages\pandas\core\indexing.py
in
_get_listlike_indexer(self, key, axis, raise_missing)
1550 keyarr,indexer,new_indexer=ax._reindex_non_unique
(keyarr)
1551
-> 1552 self._validate_read_indexer(
1553 keyarr,indexer,o._get_axis_number
(axis),raise_missing=raise_missing
1554 )
~\anaconda3\lib\site-packages\pandas\core\indexing.py
in
_validate_read_indexer
(self, key, indexer, axis, raise_missing)
1652 # just raising
1653 ifnot(ax.is_categorical()orax.is_interval()
)
:
-> 1654 raise KeyError(
1655 "Passing list-likes to .loc or [] with any missing labels "
1656 "is no longer supported, see "

KeyError: '傳遞列表狀物件到 .loc 或 [] 且存在任何缺失標籤不再受支援,請參閱 https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike'

一種解決方法是直接檢查索引中的值。

"When is Avengers next movie?"in movies.index

輸出

False

如果您想忽略錯誤並繼續,可以使用以下方法

movies.query("title in ('Avatar','When is Avengers next Movie?')")


budget vote_average vote_count
title
Avatar 237000000 7.2 11800

更新於: 2020年11月10日

741 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.