如何使用条件索引获取单元格上的标量值 [英] How to get scalar value on a cell using conditional indexing

查看:68
本文介绍了如何使用条件索引获取单元格上的标量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()?

>>> 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'>

推荐答案

首先,最好从.loc访问行和列索引:

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

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

第二,您总是可以在序列或数据帧上使用.values来获取底层的numpy矩阵:

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

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

最后,如果您对原始问题的条件索引"不感兴趣,则还可以使用特定的访问器来从DataFrame中获取单个标量值:

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).

这篇关于如何使用条件索引获取单元格上的标量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆