Imran Ahmad Ghazali
Imran Ahmad Ghazali

Reputation: 625

How to replace dataframe columns on given condition?

I have a Dataframe , in which i have two columns, first_columns and second_columns. first_columns is id and second_columns is room number. enter image description here

As you can see from pic that, particular id person serve on different room number. Now i want to replace all the second_columns columns with 1 and zero on given condition

1) if particular first_columns column id person does't not serve in 9, 10 and 11, then replace all the room number with 1, if he work then replace all room number with 0.

In above picture, first_columns id 3737 doest not work in room 9,10, and 11. then all the row of 3737 room number will be replace by 1.

Upvotes: 1

Views: 44

Answers (1)

jezrael
jezrael

Reputation: 862901

I think need groupby with transform for compare by sets, last invert mask by ~ and convert to integers:

df['new'] = ((~df.groupby('first_column')['second_column']
                .transform(lambda x: set(x) >=set([9,10,11])))
                .astype(int))
print (df)
    first_column  second_column  new
0           3767              2    1
1           3767              4    1
2           3767              6    1
3           6282              2    0
4           6282              9    0
5           6282             10    0
6           6282             11    0
7          10622              0    1
8          13096              7    1
9          13096             10    1
10         13896             11    1

Upvotes: 1

Related Questions