Skip to content
Advertisement

Comparison of a Dataframe column values with a list

Consider this Dataframe:

JavaScript

This is the code to get values of column C, where it is the first row of each group (Column A):

JavaScript

So first will be: (100, 200, 300).

Now I want to add new column which it will be 1 if value of column C for row is in firsts otherwise it will be 0.

A B C D
1 10 100 1
1 15 150 0
2 20 200 1
2 25 250 0
3 30 300 1
3 35 350 0

I used this:

JavaScript

But the output is:

A B C D
1 10 100 0
1 15 150 0
2 20 200 0
2 25 250 0
3 30 300 0
3 35 350 0

I appreciate if anyone explain why my solution is wrong and what is actual solution to this problem?

Advertisement

Answer

You can use isin method:

JavaScript

The reason your approach fails is that python in operator check the index of a Series instead of the values, the same as how a dictionary works:

JavaScript

Modifying your method as follows works:

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