首页 > 解决方案 > “[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') "

谁能帮我改正代码??提前致谢。

标签: pythonpandasmatplotlib

解决方案


这是您的问题的有效解决方案。您始终可以使用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()

输出

在此处输入图像描述


推荐阅读