mArk
mArk

Reputation: 658

Fill the row in a data frame with a specific value based on a condition on the specific column

I have a data frame df:

df=
A   B   C  D
1   4   7  2
2   6  -3  9
-2  7   2  4

I am interested in changing the whole row values to 0 if it's element in the column C is negative. i.e. if df['C']<0, its corresponding row should be filled with the value 0 as shown below:

df=
A   B   C  D
1   4   7  2
0   0   0  0
-2  7   2  4

Upvotes: 0

Views: 65

Answers (1)

cs95
cs95

Reputation: 402303

You can use DataFrame.where or mask:

df.where(df['C'] >= 0, 0)

   A  B  C  D
0  1  4  7  2
1  0  0  0  0
2 -2  7  2  4

Another option is simple masking via multiplication:

df.mul(df['C'] >= 0, axis=0)

   A  B  C  D
0  1  4  7  2
1  0  0  0  0
2 -2  7  2  4

You can also set values directly via loc as shown in this comment:

df.loc[df['C'] <= 0] = 0
df

   A  B  C  D
0  1  4  7  2
1  0  0  0  0
2 -2  7  2  4

Which has the added benefit of modifying the original DataFrame (if you'd rather not return a copy).

Upvotes: 1

Related Questions