pandas 标签不在列表中和 KeyError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44352271/
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
Label Not In List and KeyError
提问by Danny W
I'm trying to get the value of a specific cell.
我正在尝试获取特定单元格的值。
main_id name code
0 1345 Jones 32
1 1543 Hyman 62
2 9874 Buck 86
3 2456 Slim 94
I want the cell that says code=94, as I already know the main_id but nothing else.
我想要显示 code=94 的单元格,因为我已经知道 main_id 但没有别的。
raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
'name': ['Jones', 'Hyman', 'Buck', 'Slim'],
'code': [32, 62, 86, 94]}
df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])
v=df.loc[str(df['main_id']) == str(2456)]['code'].values
print(df.loc['name'])
The print(df.loc['name'])
claims the label is not in index
该print(df.loc['name'])
索赔标签不在索引中
And the v=df.loc[str(df['main_id']) == str(2456)]['code'].values
says 'KeyError False'
并且v=df.loc[str(df['main_id']) == str(2456)]['code'].values
说“KeyError False”
回答by ayhan
df.loc['name']
raises a KeyError because name
is not in the index; it is in the columns. When you use loc
, the first argument is for index. You can use df['name']
or df.loc[:, 'name']
.
df.loc['name']
引发 KeyError 因为name
不在索引中;它在列中。使用时loc
,第一个参数用于索引。您可以使用df['name']
或df.loc[:, 'name']
。
You can also pass boolean arrays to loc
(both for index and columns). For example,
您还可以将布尔数组传递给loc
(索引和列)。例如,
df.loc[df['main_id']=='2456']
Out:
main_id name code
3 2456 Slim 94
You can still select a particular column for this, too:
您仍然可以为此选择特定的列:
df.loc[df['main_id']=='2456', 'code']
Out:
3 94
Name: code, dtype: int64
With boolean indexes, the returning object will always be a Series even if you have only one value. So you might want to access the underlying array and select the first value from there:
使用布尔索引,即使您只有一个值,返回的对象也将始终是一个系列。所以你可能想要访问底层数组并从那里选择第一个值:
df.loc[df['main_id']=='2456', 'code'].values[0]
Out:
94
But better way is to use the item
method:
但更好的方法是使用该item
方法:
df.loc[df['main_id']=='2456', 'code'].item()
Out:
94
This way, you'll get an error if the length of the returning Series is greater than 1 while values[0]
does not check that.
这样,如果返回的 Series 的长度大于 1 而values[0]
没有检查它,你就会得到一个错误。
回答by MaxU
Alternative solution:
替代解决方案:
In [76]: df.set_index('main_id').at['2456','code']
Out[76]: 94