![](/img/trans.png)
[英]Type error: only integer scalar arrays can be converted to a scalar index when doing .loc with pandas DataFrame
[英]error “can only convert an array of size 1 to a Python scalar” when I try to get the index of a row of a pandas dataframe as an integer
我有一个包含股票代码和许多其他列的 excel 文件。 我在下面有一个 excel 文件的简化版本:
象征 | 行业 | |
---|---|---|
0 | 苹果 | 技术制造 |
1 | 微软 | 技术制造 |
2 | 特斯拉 | 电动汽车制造 |
从本质上讲,我试图根据符号获得行业。 例如,如果我使用“AAPL”,我想获得“技术制造”。 到目前为止,这是我的代码。
import pandas as pd
excel_file1 = 'file.xlsx'
df = pd.read_excel(excel_file1)
stock = 'AAPL'
row_index = df[df['Symbol'] == stock].index.item()
industry = df['Industry'][row_index]
print(industry)
尝试获取 row_index 后,出现错误:“ValueError:只能将大小为 1 的数组转换为 Python 标量”
有人可以解决这个问题吗? 还可以说 row_index 有效:这段代码(下面)是否正确?
industry = df['Industry'][row_index]
利用:
stock = 'AAPL'
industry = df[df['Symbol'] == stock]['Industry'][0]
OR: ,如果要使用index
进行搜索,请使用df.loc
:
stock = 'AAPL'
industry = df.loc[df[df['Symbol'] == stock].index, 'Industry'][0]
但是第一个好多了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.