Skip to content
Advertisement

Loop through unique values in a column to check another column and create another column – pandas

I would like to create a function to go through each unique value in a column and check if another column contains a value and then create a column that shows the result.

For example: for each unique ID in df, check if the stats is A then create a result column:

df:

ID Status
1 A
1 B
2 B
2 C

new_df:

ID Status Result A?
1 A YES
2 B NO

I started off with

JavaScript

If anyone can share some thoughts I would much appreciate.

Advertisement

Answer

I am not sure if I understand the rules correctly. Should I always take the first occurrence of the ID? Then the second row in your expected output is wrong.

You can use numpy.where

JavaScript

to get this:

JavaScript

Edit: Your desired output is ambiguous, two things you can do:

JavaScript

gives you:

JavaScript

Or:

JavaScript

which gives you:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement