从数据帧熊猫中获取单个值

时间:2018-01-24 13:00:47

标签: python pandas

我有一个数据框A:

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

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

所以我试过了:

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

但我看到.get_value()已被删除,并且:

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

给出了这个错误:

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

编辑:

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

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

 print(number)

 2    1.4
 Name: T, dtype: float64

这样做时:

 number2 = 1.3
 if (number != number2):

我明白了:

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

2 个答案:

答案 0 :(得分:1)

过滤后,您获得one item Series,因此,对于选择第一个值,可以使用iat

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

但是如果mask返回更多值,请获取:

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

可以使用相同的aproach - 选择条件的第一个值:

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

答案 1 :(得分:1)

以上内容将引发错误idx,但未定义,访问索引的默认方式是 dataframe.index 而不是idx

应该是

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