user3605780
user3605780

Reputation: 7072

Get single value from dataframe pandas

I have a dataframe 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'

So I tried:

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

but I see .get_value() is depricated and:

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

Upvotes: 3

Views: 12723

Answers (2)

RESHAM JHANGIANI
RESHAM JHANGIANI

Reputation: 31

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

It should rather be

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

Upvotes: 3

jezrael
jezrael

Reputation: 862406

After filtering you get one item Series, so for select first value is possible use 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

Upvotes: 9

Related Questions