我无法按列名称提取数据?

我刚刚开始使用 pandas 库。尽管我进行了研究,但我仍然没有弄清楚。我想提取名为 q 的列的数据。但它给出了一个错误。我怎样才能做到这一点?


import pandas as pd

data = 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]"


扬帆大鱼
浏览 147回答 4
4回答

呼啦一阵风

修复data/df混乱首先,确实不需要这条线df&nbsp;=&nbsp;pd.DataFrame(data)正如函数data返回的那样,已经是一个 Pandas DataFrame 了pd.read_excel。df相反,我建议省略这一行并简单地使用以下内容(在本答案的其余部分中,我将使用此函数来引用使用此函数生成的 Pandas DataFrame)。df&nbsp;=&nbsp;pd.read_excel('test1.xlsx')从列返回 Pandas 系列q假设这q是你的列的名称df:df['q']将返回代表该列的 Pandas Series&nbsp;q。如果您想使用df.loc此索引方法,则需要将一系列行作为第一项返回,并将可选范围的列作为第二项返回。q假设您正在寻求返回可以使用的列的所有行。df.loc[:,&nbsp;'q']从列返回值的 Numpy 数组q你可以使用:df['q'].values返回包含q列中存储的值的 Numpy 数组。

牛魔王的故事

您只需申请.values财产即可。它将返回 pandas 列中值的 numpy 数组。喜欢df['q'].values。因此导入 Numpy 来使用它。另一种是df['q']返回pandas系列的q列。我不会使用df.loc硬语法,但您仍然可以尝试df.loc[:, 'q']不索引而不是切片df.loc

慕桂英546537

您不需要使用索引和loc().&nbsp;尝试一下:df.loc[:,&nbsp;'q']这将获取:指定列 (&nbsp;q) 的所有行 ( )。

aluckdog

你可以只使用:print(df['q'])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python