【发布时间】:2020-05-04 18:07:24
【问题描述】:
我目前遇到这个错误:
KeyError: "['Malaysia' 'Singapore'] 不在索引中"
错误指向:
---> 37 wide_data = wide_data[['马来西亚','新加坡']]
使用print(wide_data.columns) 检查 wide_data 后,它会返回:
MultiIndex([( 'total_cases', 'Malaysia'),
( 'total_cases', 'Singapore'),
( 'new_cases', 'Malaysia'),
( 'new_cases', 'Singapore'),
('total_deaths', 'Malaysia'),
('total_deaths', 'Singapore'),
( 'new_deaths', 'Malaysia'),
( 'new_deaths', 'Singapore')],
names=[None, 'location'])
两者都存在。我不确定我的代码哪里出错了。
以下是我使用的代码 sn-p 和 Dataset:
import plotly.express as px
df = pd.read_csv('covid-data-2020.csv', index_col='date', parse_dates=True)
data = df[df.location.isin(['Malaysia', 'Singapore'])]
wide_data = data.pivot(columns='location', values=list(data.columns[2:6]))
wide_data = wide_data[['Malaysia','Singapore']]
wide_data.reset_index(level=0, inplace=True)
fig = px.line(wide_data.melt(id_vars='date'), x='date', y='value', color='location')
fig.update_yaxes(title='Malaysia vs Singapore')
fig.show()
【问题讨论】:
-
如果
covid-data-2020.csv在某处可用,您应该输入 URL,以便每个人都更容易尝试代码并提出解决方案。 -
@FxIII 为此添加了超链接。谢谢提醒
-
这是您的 csv 文件的链接吗? covid.ourworldindata.org/data/owid-covid-data.csv
-
是的,就是链接
标签: python pandas jupyter-notebook