Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

python - Find particular string and value for it in Pandas data frame

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...