pandas 熊猫键盘错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37170416/
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-14 01:13:41  来源:igfitidea点击:

Pandas Keyerror

pythonpandas

提问by jincept

I have a very simple code:

我有一个非常简单的代码:

stats2 = {'a':[1,2,3,4,5,6],
         'b':[43,34,65,56,29,76],
         'c':[65,67,78,65,45,52],
         'cac':['mns','ab','cd','cd','ab','k']}
f2 = pd.DataFrame(stats2)
f2.set_index(['cac'], inplace = True)
print(f2.ix['mns'])
print(f2['mns'])

f2.ix['mns'] works just fine. However, f2['mns'] reports KeyError. I am trying to understand why it does that. Is that how pandas work? Do I have to use ix even though I have set the index before?

f2.ix['mns'] 工作得很好。但是, f2['mns'] 报告 KeyError。我试图理解它为什么这样做。Pandas就是这样工作的吗?即使我之前设置了索引,我是否必须使用 ix?

回答by Nickil Maveli

This is your original dataframe:

这是您的原始数据框:

>>> df

   a   b   c  cac
0  1  43  65  mns
1  2  34  67   ab
2  3  65  78   cd
3  4  56  65   cd
4  5  29  45   ab
5  6  76  52    k


>>> df.set_index(['cac'], inplace=True)
>>> df

     a   b   c
cac           
mns  1  43  65
ab   2  34  67
cd   3  65  78
cd   4  56  65
ab   5  29  45
k    6  76  52

So, setting the index in pandas is simply replacing the before counter values(0,1,2,...,5) to the new row values i.e (mns, ab,...,k) of caccolumn name.

因此,在pandas 中设置索引只是将之前的计数器值(0,1,2,...,5) 替换为新的行值,即cac列名的(mns, ab,...,k) 。

>>> df.ix['mns']

a     1
b    43
c    65

This command specifically searches for row in the index column, cacwhose value is equal to mnsand retrieves it's corresponding elements.

该命令专门搜索索引列中的行,cac其值等于mns并检索其对应的元素。

Note:As mnsis not a column name of the dataframe, df['mns']throws a key error.

注意:由于mns不是数据df['mns']框的列名,会引发关键错误。