Michael Zeng
Michael Zeng

Reputation: 80

How to replace the value of a column base on the condition of another 2 columns?

if the value in the column 'active' is equal to 0, or if the value in 'category' is equal to NaN, then the value in that specific row in 'position' should = 0.

Before;

active position category
1       1      NaN
1       2      NaN
1       1        a
0       1        a
0       1        a
1       2        a
1       1        b
0       1        b
1       2        b

after:

active position category
1       0      NaN
1       0      NaN
1       1        a
0       0        a
0       0        a
1       2        a
1       1        b
0       0        b
1       2        b

Upvotes: 0

Views: 51

Answers (1)

cs95
cs95

Reputation: 402323

One possible solution, IIUC. Set all rows fulfilling your condition to 0:

In [355]: df.loc[(df.active == 0) | (df.category.isnull()), 'position'] = 0; df
Out[355]: 
   active  position category
0       1         0      NaN
1       1         0      NaN
2       1         1        a
3       0         0        a
4       0         0        a
5       1         2        a
6       1         1        b
7       0         0        b
8       1         2        b

All other rows remain unchanged.

Upvotes: 1

Related Questions