1

I am searching for a particular name in column 'names' and its value. for e.g, I want to search for string 'pqr' in column 'names' and get its values from 'Total' column, which is 304 so the final output is 304.

Input:

    names       Total
0    abc          186
1    xyz          545
2    pqr          304
3    lmn          405
4    def            0

3 Answers 3

1

Use DataFrame.loc with mask and then select for first match value converted values to array and select first one:

df.loc[df['names'] == 'pqr', 'Total'].to_numpy()[0]

#or select first match value by position
df.loc[df['names'] == 'pqr', 'Total'].iat[0]

Or for more general solution working also if no match use:

next(iter(df.loc[df['names'] == 'pqr', 'Total']), 'no match')
Sign up to request clarification or add additional context in comments.

2 Comments

can I know why call to_numpy() here?
@billz - it is solution for get first value, because get one element Series from df.loc[df['names'] == 'pqr', 'Total']
0

This code fits your example:

df[df['names'] == 'pqr']['Total']

Comments

0
df.loc[df['names']=='pqr','Total']
2    304
Name: Total, dtype: int64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.