The Python Oracle

Extract column value based on another column in Pandas

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Extract Column Value Based On Another Column In Pandas
00:26 Answer 1 Score 67
00:37 Accepted Answer Score 388
00:53 Answer 3 Score 91
01:03 Answer 4 Score 23
01:12 Thank you

--

Full question
https://stackoverflow.com/questions/3668...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #dataframe

#avk47



ACCEPTED ANSWER

Score 388


You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'



ANSWER 2

Score 91


You can try query, which is less typing:

df.query('B==3')['A']



ANSWER 3

Score 67


Try:

df[df['B']==3]['A'].item()

assuming df is your pandas.DataFrame.




ANSWER 4

Score 23


Use df[df['B']==3]['A'].values[0] if you just want item itself without the brackets