<module>中的键错误回溯(最近一次调用上次)<ipythoninput2861ee9b9495dc1>()

2024-09-26 18:20:28 发布

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

我正试图用哥伦比亚新冠病毒-19的数据绘制一个条形图。我制作了一个包含城市、案例数量和日期的数据框架,然后添加了一些美学元素和一个包含年份和国家的专栏。但是当代码试图读取数据帧时,我得到了这个错误。我不知道它为什么认不出钥匙

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML

dat=db.pivot_table(values='Casos',index=["Ciudad",'Fecha'],
                   aggfunc={'count'})

dat.reset_index(inplace=True)
dat['Fecha']=dat["Fecha"]

dat

año=[]
for i in range(3927):
  año.append(2020)

group=[]
for k in range(3927):
  group.append('Colombia')

dat['año']=año
dat['group']=group

colors = dict(zip(
    ['Arauca', 'Armenia', 'Barranquilla', 'Bogotá D.C.', 'Bucaramanga',
       'Cali', 'Cartagena de Indias', 'Cúcuta', 'Florencia', 'Ibagué',
       'Inírida', 'Leticia', 'Manizales', 'Medellín', 'Mitú', 'Mocoa',
       'Montería', 'Neiva', 'Pasto', 'Pereira', 'Popayán',
       'Puerto Carreño', 'Quibdó', 'Riohacha', 'San Andrés',
       'San José del Guaviare', 'Santa Marta', 'Sincelejo', 'Tunja',
       'Valledupar', 'Villavicencio', 'Yopal'],
    ["#adb0ff", "#ffb3ff", "#90d595", "#e48381", "#aafbff", "#f7bb5f", "#eafb50",'#c0c0c0','#808080',
     '#ff0000','#ffff00','#808000','#00ff00','#008000','#00ffff','#008080','#000080','#ff00ff',
     '#800080','#f0f8ff','#faebd7','#7fffd4','#f0ffff','#f5f5dc','#ffe4c4','#000000','#8a2be2',
     '#a52a2a','#7fff00','#ff8c00','#cd5c5c','#20b2aa']
))
group_lk = dat.set_index('Ciudad')['group'].to_dict()

dff = dat[dat['año'].eq(2020)].sort_values(by='count', ascending=True).tail(10)
dff

dff.keys()

fig, ax = plt.subplots(figsize=(15, 8))

def draw_barchart(current_year):
    dff = dat[dat['año'].eq(current_year)].sort_values(by='count', ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['Ciudad'], dff['count'], color=[colors[group_lk[x]] for x in dff['Ciudad']])
    dx = dff['count'].max() / 200
    for i, (value, name) in enumerate(zip(dff['count'], dff['Ciudad'])):
        ax.text(value-dx, i,     name,           size=14, weight=600, ha='right', va='bottom')
        ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')
        ax.text(value+dx, i,     f'{value:,.0f}',  size=14, ha='left',  va='center')
    ax.text(1, 0.4, current_year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
    ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777')
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x', colors='#777777', labelsize=12)
    ax.set_yticks([])
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0, 1.15, 'The most populous cities in the world from 1500 to 2018',
            transform=ax.transAxes, size=24, weight=600, color='#d62929', ha='left', va='top')
    ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, color='#777777', ha='right',
            bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
    plt.box(False)
    
draw_barchart(2020) 

错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-286-1ee9b9495dc1> in <module>()
     25     plt.box(False)
     26 
---> 27 draw_barchart(2020)

1 frames
<ipython-input-286-1ee9b9495dc1> in <listcomp>(.0)
      4     dff = dat[dat['año'].eq(current_year)].sort_values(by='count', ascending=True).tail(10)
      5     ax.clear()
----> 6     ax.barh(dff['Ciudad'], dff['count'], color=[colors[group_lk[x]] for x in dff['Ciudad']])
      7     dx = dff['count'].max() / 200
      8     for i, (value, name) in enumerate(zip(dff['count'], dff['Ciudad'])):

KeyError: 'Colombia'

Tags: textintrueforsizevaluecountgroup

热门问题