如何处理KeyError:0或KeyError:1的问题

2024-04-19 21:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和数据科学领域的新手,我正在尝试使用不同的数据集。你知道吗

在本例中,我使用的是来自quandl的住房价格指数,但不幸的是,当我需要从wiki页面获取缩写名称时,总是得到相同的Error KeyError。你知道吗

import quandl
import pandas as pd
#pull every single housing price index from quandl

#quandl api key
api_key = 'xxxxxxxxxxxx'

#get stuff from quandl
df = quandl.get('FMAC/HPI_AK',authtoken = api_key) #alaska \
##print(df.head())

#get 50 states using pandas read html from wikipedia
fifty_states = pd.read_html('https://en.wikipedia.org       /wiki/List_of_states_and_territories_of_the_United_States')
##print(fifty_states[0][1]) #first data frame is index 0, #looking for     column 1,#from element 1 on

#get quandl frannymac query names for each 50 state
for abbv in fifty_states[0][1][2:]:
#print('FMAC/HPI_'+str(abbv))

所以我在以下步骤中遇到了问题:

#get 50 states using pandas read html from wikipedia
fifty_states = pd.read_html('https://en.wikipedia.org       /wiki/List_of_states_and_territories_of_the_United_States')
##print(fifty_states[0][1]) #first data frame is index 0, #looking for     column 1,#from element 1 on

我尝试了不同的方法来获取缩写,但都不起作用

for abbv in fifty_states[0][1][2:]:
#print('FMAC/HPI_'+str(abbv)) 

for abbv in fifty_states[0][1][1:]:
#print('FMAC/HPI_'+str(abbv))

始终键错误:0

我只需要这一步来工作,并获得以下输出:

FMAC/HPI_AL,
FMAC/HPI_AK,
FMAC/HPI_AZ,
FMAC/HPI_AR,
FMAC/HPI_CA,
FMAC/HPI_CO,
FMAC/HPI_CT,
FMAC/HPI_DE,
FMAC/HPI_FL,
FMAC/HPI_GA,
FMAC/HPI_HI,
FMAC/HPI_ID,
FMAC/HPI_IL,
FMAC/HPI_IN,
FMAC/HPI_IA,
FMAC/HPI_KS,
FMAC/HPI_KY,
FMAC/HPI_LA,
FMAC/HPI_ME

对美国50个州的数据进行分析。你知道吗

有人能告诉我我做错了什么吗?干杯


Tags: of数据fromforreadgethtmlwikipedia
1条回答
网友
1楼 · 发布于 2024-04-19 21:34:08

请注意,fifty_states是数据帧的列表,填充了 源页中表的内容。你知道吗

其中第一个(在50个州的指数0)是美国各州表。你知道吗

如果您不知道数据帧中的列名(例如df), 要从中获取列1(计数形式0),请运行:

df.iloc[:, 1]

所以,既然我们想要五十个州的这个列,运行:

fifty_states[0].iloc[:, 1]

您的代码失败,因为您试图将[1]应用于此数据帧, 但是这个数据帧没有名为1的列。你知道吗

注意,例如fifty_states[0][('Cities', 'Capital')]给出了正确的结果, 因为:

  • 这个数据帧在列上有一个多索引
  • 其中一列在第一个多索引级别具有城市 第二级资本。你知道吗

回到你的代码,运行:

for abbv in fifty_states[0].iloc[:, 1]:
    print('FMAC/HPI_' + str(abbv))

请注意,不需要[2:]。您可能想跳过最初的两行 包含列名的<;table>;HTML标记, 但在熊猫中,它们实际上保存在列的多索引中, 所以要得到所有的值,你不需要跳过任何东西。你知道吗

如果要将这些字符串作为列表,以便将来使用,代码可以是:

your_list = ('FMAC/HPI_' + fifty_states[0].iloc[:, 1]).tolist()

相关问题 更多 >