我刚刚开始使用 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
提交
取消