python - “[Index(['', ''], dtype='object')] are in the [columns]” in plotting a Line Plots using matplotlib
问题描述
我正在尝试使用Canada Immigration的数据绘制一条线。我的代码如下...
import pandas as pd
df_canada = pd.read_excel('Canada.xlsx', sheet_name = 'Canada by Citizenship (2)')
df_canada.set_index('OdName', inplace = True)
import matplotlib.pyplot as plt
years = list (map(str, range(1980, 2014)))
df_canada['Total'] = df_canada[1980] + df_canada[1981]+ df_canada[1982]+ df_canada[1983]+ df_canada[1984]+ df_canada[1985]+ df_canada[1986]+ df_canada[1987]+ df_canada[1988]+ df_canada[1989]+ df_canada[1990]+ df_canada[1991]+ df_canada[1992]+ df_canada[1993]+ df_canada[1994]+ df_canada[1995]+ df_canada[1996]+ df_canada[1997]+ df_canada[1998]+ df_canada[1999]+ df_canada[2000]+ df_canada[2001]+ df_canada[2002]+ df_canada[2003]+ df_canada[2004]+ df_canada[2005]+ df_canada[2006]+ df_canada[2007]+ df_canada[2008]+ df_canada[2009]+ df_canada[2010]+ df_canada[2011]+ df_canada[2012] + df_canada[2013]
df_canada.loc['Haiti', years].plot(kind = 'line')
plt.title('Immigration from Albania')
plt.ylabel('Number of Immigrants')
plt.xlabel('years')
plt.show()
但是代码出现错误“KeyError:”None of [Index(['1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987', ' 1988',\n '1989', '1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997',\n '1998', '1999' , '2000', '2001', '2002', '2003', '2004', '2005', '2006',\n '2007', '2008', '2009', '2010', '2011' , '2012', '2013'],\n dtype='object')] 在 [index]"" 执行行 "df_canada.loc['Haiti', years].plot(kind = 'line') "
谁能帮我改正代码??提前致谢。
解决方案
这是您的问题的有效解决方案。您始终可以使用iloc
通过数字访问列:
import pandas as pd
import matplotlib.pyplot as plt
df_canada = pd.read_excel('Canada.xlsx', sheet_name = 'Canada by Citizenship (2)')
#summing all the years in one line instead of typing years individually. Years start from column 9.
df_canada['total'] = df_canada.iloc[:,9:].sum(axis=1)
#Filtering the data country in standard pandas style and select column 9 to second last column (last column is total)
df_canada[df_canada['OdName']=='Haiti'].iloc[:,9:-1].T.plot(kind = 'line')
plt.title('Immigration from Haiti')
plt.ylabel('Number of Immigrants')
plt.xlabel('years')
plt.legend(['number'])
plt.show()
输出:
推荐阅读
- python - 覆盖列表到 unicode python 3.6
- mysql - 数据不变时是否需要更新
- excel - 具有可变输入的 Hlookup
- reactjs - react-google-maps 中的替代路线
- java - 我在 tomcat7 服务器中有一个端口问题 在 http://localhost:8080/ 上运行战争,但使用 maven 项目的实际端口是 8090
- php - PHP & MySQL - 未定义索引:尝试使用 PHP 进行小查询时的 VIN
- python - 使用 GPU 构建的 TensorFlow 1.8 Cmake 在 Windows 10 上失败并出现 MSB6006 错误
- xslt - XSLT 按名称和总和值分组
- angular6 - 可以激活问题
- linux - 如何将远程 tarball 提取到本地计算机上