pandas 从数据框熊猫中获取单个值

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

Get single value from dataframe pandas

pythonpandas

提问by user3605780

I have a dataframe A:

我有一个数据框 A:

       's'   'S'   'T'
 0     'abc'  'a'   12
 1     'def'  'b'   15
 2     'abc'  'b'   1.4

Now I want to have the value of 'T' where 's' == 'abc' and 'S' == 'b'

现在我想拥有 'T' 的值,其中 's' == 'abc' 和 'S' == 'b'

So I tried:

所以我试过:

  idx = (A['s'] == 'abc') & (A['S'] == 'b')

but I see .get_value() is depricated and:

但我看到 .get_value() 已被弃用,并且:

 number = A.at[idx,'T']

gives this error:

给出这个错误:

ValueError: At based indexing on an integer index can only have integer indexers

EDIT:

编辑:

 number = A.loc[idx, 'T']

returns a dataframe and not the value (integer or float)

返回数据帧而不是值(整数或浮点数)

 print(number)

 2    1.4
 Name: T, dtype: float64

When doing this:

这样做时:

 number2 = 1.3
 if (number != number2):

I get:

我得到:

  ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

回答by jezrael

After filtering you get one item Series, so for select first value is possible use iat:

过滤后你得到one item Series,所以选择第一个值是可能的使用iat

number = A.loc[idx,'T'].iat[0]
print (number)
14

But if mask return more values, get:

但是如果掩码返回更多值,得到:

print (A)
     s  S   T
0  abc  a  12
1  abc  b  15
2  abc  b  14

idx = (A['s'] == 'abc') & (A['S'] == 'b')
print (idx)
0    False
1     True
2     True
dtype: bool

number = A.loc[idx,'T']
print (number)
1    15
2    14
Name: T, dtype: int64

Here is possible use same aproach - select first value of condition:

这里可以使用相同的方法 - 选择条件的第一个值:

number = A.loc[idx,'T'].iat[0]
print (number)
15

回答by RESHAM JHANGIANI

The above will throw an error of idx not defined, the default way to access index is dataframe.indexand not idx

上面会抛出idx not defined的错误,默认访问index的方式是dataframe.index而不是idx

It should rather be

应该是

number = A.loc[A.index,'T'].iat[0]