我剛剛開始使用 pandas 庫。盡管我進行了研究,但我仍然沒有弄清楚。我想提取名為 q 的列的數據。但它給出了一個錯誤。我怎樣才能做到這一點?import pandas as pddata = pd.read_excel('test1.xlsx')df = pd.DataFrame(data)print(df.loc[df['q']]) 錯誤: Traceback (most recent call last): File "c:/Users/sabca/visual studio code projects/webscraping/pandastest.py", line 11, in <module> print(df.loc[df['q']]) File "C:\Users\sabca\AppData\Local\Programs\Python\Python38\lib\site- packages\pandas\core\indexing.py", line 879, in __getitem__ return self._getitem_axis(maybe_callable, axis=axis) File "C:\Users\sabca\AppData\Local\Programs\Python\Python38\lib\site- packages\pandas\core\indexing.py", line 1099, in _getitem_axis return self._getitem_iterable(key, axis=axis) File "C:\Users\sabca\AppData\Local\Programs\Python\Python38\lib\site- packages\pandas\core\indexing.py", line 1037, in _getitem_iterable keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False) File "C:\Users\sabca\AppData\Local\Programs\Python\Python38\lib\site- packages\pandas\core\indexing.py", line 1254, in _get_listlike_indexer self._validate_read_indexer(keyarr, indexer, axis, raise_missing=raise_missing) File "C:\Users\sabca\AppData\Local\Programs\Python\Python38\lib\site- packages\pandas\core\indexing.py", line 1298, in _validate_read_indexer raise KeyError(f"None of [{key}] are in the [{axis_name}]") KeyError: "None of [Index(['qwe1', 'asdf1', 'adfs4', 'wer7', 'tyu1', 'ghfhg5'], dtype='object')] are in the [index]"
4 回答

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
修復data
/df
混亂
首先,確實不需要這條線
df = pd.DataFrame(data)
正如函數data
返回的那樣,已經是一個 Pandas DataFrame 了pd.read_excel
。
df
相反,我建議省略這一行并簡單地使用以下內容(在本答案的其余部分中,我將使用此函數來引用使用此函數生成的 Pandas DataFrame)。
df = pd.read_excel('test1.xlsx')
從列返回 Pandas 系列q
假設這q
是你的列的名稱df
:
df['q']
將返回代表該列的 Pandas Series q
。
如果您想使用df.loc
此索引方法,則需要將一系列行作為第一項返回,并將可選范圍的列作為第二項返回。q
假設您正在尋求返回可以使用的列的所有行。
df.loc[:, 'q']
從列返回值的 Numpy 數組q
你可以使用:
df['q'].values
返回包含q
列中存儲的值的 Numpy 數組。

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
您只需申請.values
財產即可。它將返回 pandas 列中值的 numpy 數組。喜歡df['q'].values
。因此導入 Numpy 來使用它。
另一種是df['q']
返回pandas系列的q列。
我不會使用df.loc
硬語法,但您仍然可以嘗試df.loc[:, 'q']
不索引而不是切片df.loc
添加回答
舉報
0/150
提交
取消