2017-03-20 91 views
0

我想用大熊猫 得到城市的状态下最大数量(“CTYNAME”)(“STNAME”)我有一个数据帧为什么我会得到KeyError异常在熊猫的Python

df_filtered = census_df.copy().filter(items=['SUMLEV','STNAME','CTYNAME']) 
df_filtered = df_filtered.set_index(['STNAME']) 
state_df['STNAME'] = df.index.tolist() 
state_df['STNAME'] = state_df['STNAME'].drop_duplicates() 
state_df = state_df['STNAME'].dropna() 
state_df = pd.DataFrame(state_df) 
state_df.set_index(['STNAME']) 

for state in state_df: 
    state_df['COUNT'] = df.loc[state].count() 

对于一些因为即使我将索引设置为州名('STNAME'),索引也是一堆整数而不是州名(即阿拉斯加州,犹他州等)。

当我尝试运行它给我一个关键错误

KeyError: 'the label [STNAME] is not in the [index]' 

回答

0

代码当你做for _ in df你实际上是遍历头。 尝试遍历系列state_df['STNAME']

for state in state_df['STNAME']: 
    # do stuff here with state 

否则,使用state_df.iterrows()遍历行。如果“STNAME”是您的索引,您可以这样做:

for row in state_df.iterrows(): 
    state_name = row[0] 
    # do stuff here with state name 
+0

如何重复使用iterrows?我尝试着使用下一个(state_df.iterrows())[1],并且由于某种原因,它一直给我同样的记录“阿拉巴马州”。 –

+0

当我打印(state_df)时,它显示左边的整数列表和右边的STNAME(州名) - 它们都是唯一的。我只是无法弄清楚如何迭代状态名... 另外我试着做(〜(next(state_df.iterrows())[1] .empty())):但是抛出了一个typeError “Bool”对象不可调用 –

+0

我已更新我的答案。按照我的第一个示例所示,尝试迭代“STNAME”列。 – Lgiro

0

您的索引未设置。尝试这个。

编辑代码:

df_filtered = df_filtered.set_index('STNAME') 
+0

@Linkx_lair。尝试这个。希望这会有所帮助。 – Dheeraj

+0

我试过,但是当我尝试使用index.tolist()打印出索引列表时,它显示了一个整数列表。我不知道发生了什么,为什么我不能将索引设置为州名('STNAME') –