Extract column value based on another column in Pandas
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:33 Accepted answer (Score 360)
00:56 Answer 2 (Score 77)
01:09 Answer 3 (Score 53)
01:25 Answer 4 (Score 22)
01:42 Thank you
--
Full question
https://stackoverflow.com/questions/3668...
Accepted answer links:
[loc]: http://pandas.pydata.org/pandas-docs/sta...
[iloc]: http://pandas.pydata.org/pandas-docs/sta...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:33 Accepted answer (Score 360)
00:56 Answer 2 (Score 77)
01:09 Answer 3 (Score 53)
01:25 Answer 4 (Score 22)
01:42 Thank you
--
Full question
https://stackoverflow.com/questions/3668...
Accepted answer links:
[loc]: http://pandas.pydata.org/pandas-docs/sta...
[iloc]: http://pandas.pydata.org/pandas-docs/sta...
--
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