在Python中使用Pandas使用.loc方法时出现KeyError

问题描述 投票:0回答:1

我有一个简单的项目,是使用从 Excel 工作表文件(xlsx 文件)收集的信息创建的。

这是我正在使用的信息

当我跑步时

df.iloc[1]
输出是

但是当我运行

df.loc['Amazon'] 
时,我得到了我正在寻找的关键字的KeyError

我是否需要使用特定类型的文件才能正常运行,或者我的代码中缺少简单的语法?

python pandas web-scraping data-analysis
1个回答
0
投票

您应该首先将“Name”列设置为DataFrame的索引。

df.set_index('Name', inplace=True)
// then you can use the cell value of the "Name" column to index
df.loc['Amazon']

参考:pandas.DataFrame.set_indexpandas.DataFrame.loc

© www.soinside.com 2019 - 2024. All rights reserved.