pandas KeyError: 你没有名为 <name> 的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19444659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:15:06  来源:igfitidea点击:

KeyError: u'no item named <name>'

pythonpandasdataframe

提问by user2866103

I have this function which places data into another dataframe.

我有这个功能可以将数据放入另一个数据框中。

def set_var(self,navn,periode,value):
    try:
        if navn.upper() not in self.data:
            self.data[navn.upper()]=NaN
        self.data[navn.upper()].ix[periode]=value
    except:
        print('> fejl ved genmning af:',navn,'i',periode)
        print( self.data[navn.upper()])
    return

which I then iterate like this, this fill with data:

然后我像这样迭代,这填充了数据:

for idx, val in enumerate(bd):
    if val not in ('Navn','Type','Aarstal','Referenceperiode','Registreringsnummer','nummer','navn','navn1','period', 'regnr'):
        for row in bd.itertuples():
            banker.set_var((str(row[6])+'_'+str(val)),row[60], row[idx+1])

I get the error: KeyError: u'no item named <name of first item I try to insert>'

我收到错误: KeyError: u'no item named <name of first item I try to insert>'

Why is this?

为什么是这样?

回答by nitin

A Key Error is typically because the dict object does not have the key you are requesting. It seems to me that self.data is a dict. If so, you could test your object by using has_key()... like so,

密钥错误通常是因为 dict 对象没有您请求的密钥。在我看来 self.data 是一个字典。如果是这样,您可以使用 has_key() 来测试您的对象...

if self.data.has_key(navn.upper()):
        self.data[navn.upper()]=NaN