Python 如何使用条件索引获取单元格上的标量值

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

How to get scalar value on a cell using conditional indexing

pythonpandas

提问by user4979733

I have the dataframe shown below. I need to get the scalar value of column B, dependent on the value of A (which is a variable in my script). I'm trying the loc() function but it returns a Series instead of a scalar value. How do I get the scalar value()?

我有如下所示的数据框。我需要获取 B 列的标量值,这取决于 A 的值(这是我脚本中的一个变量)。我正在尝试 loc() 函数,但它返回一个系列而不是一个标量值。我如何获得标量值()?

>>> x = pd.DataFrame({'A' : [0,1,2], 'B' : [4,5,6]})
>>> x
   A  B
0  0  4
1  1  5
2  2  6

>>> x.loc[x['A'] == 2]['B']
2    6
Name: B, dtype: int64

>>> type(x.loc[x['A'] == 2]['B'])
<class 'pandas.core.series.Series'>

采纳答案by Noah

First of all, you're better off accessing both the row and column indices from the .loc:

首先,您最好从以下位置访问行和列索引.loc

x.loc[x['A'] == 2, 'B']

Second, you can always get at the underlying numpy matrix using .valueson a series or dataframe:

其次,您始终可以在.values系列或数据帧上使用底层 numpy 矩阵:

In : x.loc[x['A'] == 2, 'B'].values[0]
Out: 6

Finally, if you're not interested in the original question's "conditional indexing", there are also specific accessors designed to get a single scalar value from a DataFrame: dataframe.at[index, column]or dataframe.iat[i, j](these are similar to .loc[]and .iloc[]but designed for quick access to a single value).

最后,如果你不是在原来的问题的“有条件索引”感兴趣的话,也有设计为从数据帧得到一个标值特定存取:dataframe.at[index, column]dataframe.iat[i, j](这些是类似于.loc[].iloc[]而设计的,以便快速访问单个值) .

回答by ihadanny

elaborating on @ShineZhang comment:

详细说明@ShineZhang 评论:

x.set_index('A').at[2, 'B']

x.set_index('A').at[2, 'B']

6

6

pd.__version__

pd.__version__

u'0.22.0'

你'0.22.0'