![](/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.