[英]Why am I getting this KeyError using multiprocessing and pandas?
[英]Why am i getting keyerror in Pandas Python
我正在嘗試使用PANDAS獲取州('STNAME')州的最大城市數('CTYNAME')我有一個數據框
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]'
當您for _ in df
操作時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
您的索引未設置。 嘗試這個。
編輯代碼:
df_filtered = df_filtered.set_index('STNAME')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.