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
1.6k views
in Technique[技术] by (71.8m points)

pandas - How to get the value of a cell based on filtering efficently

If I have a dataframe and want to have the value of a cell based on a condition/filter, it seems not to be a one line instruction.

In the example below I do not know the index at the beginning so I need to filter and then ask for index and apply it.

Is there a easier way to get the value without knowing the index upfront.

enter image description here

Edit: Easy spoken I want to have the value of the Column "Category" of the Row where the Column "No." has the value 'P1'.

question from:https://stackoverflow.com/questions/65829774/how-to-get-the-value-of-a-cell-based-on-filtering-efficently

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

1 Reply

0 votes
by (71.8m points)

You can use DataFrame.loc with specify condition and column name:

out = dfn.loc[dfn['No.'] == 'P1', 'Category']

Then out is Series, with one or more values, if no match get empty Series.

If need first value of out to scalar:

scalar = out.iat[0]

But this fail if empty Series:

out = dfn.loc[dfn['No.'] == 'aaaa', 'Category']

Then use:

scalar = next(iter(out), 'no match')

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

...