Python 我无法从数据帧获取数据

Python 我无法从数据帧获取数据,python,pandas,Python,Pandas,我正在尝试以下代码: import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt df_canada = pd.read_excel( "./Canada.xlsx", sheet_name = "Canada by Citizenship", skiprows= range(20), skipfooter=2) years =

我正在尝试以下代码:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

df_canada = pd.read_excel(
    "./Canada.xlsx",
    sheet_name = "Canada by Citizenship",
    skiprows= range(20),
    skipfooter=2)

years = list(map(str, range(1980, 2014)))
serie = df_canada.loc['Haiti', years].plot(kind='line')
但我得到了以下错误:

pandas/_libs/index.pyx在pandas中。_libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx在pandas中。_libs.index.IndexEngine.get_loc()

中的pandas/_libs/index_class_helper.pxi pandas._libs.index.int64引擎._check_type()

关键错误:“海地”

为了解决这个问题,我用以下方法编写了代码:

...
years = list(map(str, range(1980, 2014)))
df_canada.set_index('Country', inplace=True)
serie = df_canada.loc['Haiti', years].plot(kind='line')
...
但现在我得到了以下错误:

KeyError:“没有[索引(['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')]位于[索引]中。“

Canda.columns:

索引(['类型','覆盖','区域','区域名称', '注册','注册名称', “DEV”、“DevName”、1980、1981、1982、1983、, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013], dtype='object')

当然,这个索引存在于xlsx文件中

有什么想法吗

谢谢

将熊猫作为pd导入
df_canada=pd.read_excel('canada.xlsx',sheet_name='加拿大公民身份(2)'
df_canada.set_index('OdName',inplace=True)
将matplotlib.pyplot作为plt导入
#将年份更改为整数而不是字符串
年份=列表(范围(1980年、2014年))
#使用我们的年份列表简单地计算年份,而不是每年手动键入
df_canada['Total']=df_canada[年数]。总和(轴=1)
df_canada.loc[“海地”,年份]。绘图(种类=“线”)
项目名称(“阿尔巴尼亚移民”)
plt.ylabel(“移民数量”)
plt.xlabel(“年”)``
plt.show()

您能否在
Canda.columns
中提供/发布
print(df_canada.columns)
的输出。columns所有年份都是
int
s,但出于某种原因,您正在映射字符串。不要用
years=list(map(str,range(1980,2014)))
try
years=list(range(1980,2014))
或者您可以将所有列名映射到字符串:
Canda.columns=[str(column)for column in Canda.columns]
(但显然不能同时使用两者)在您的代码中设置索引后,尝试以下操作:
df_canada.loc['haid',list(range(1980,2014))。绘图(kind='line')
。或者您可以从1980:2013直接切片,如下所示:
df_canada.loc['Haiti',1980:2013]。绘图(kind='line')