Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop values in specific condition in pandas dataframe

I have a dataframe like below:

A       B       C
4.43    NaN     1.11
3.70    0.48    0.79
2.78   -0.29    1.26
1.78    2.90    1.13
40.70  -0.03    0.55
51.75   0.29    1.45
3.65    1.74    0.37
2.93    1.56    1.64
3.43    NaN     NaN
2.93    NaN     NaN
10.37   NaN     NaN

now If Column A > 7, I want to drop Column B and C like below:

A       B       C
4.43    NaN     1.11
3.70    0.48    0.79
2.78   -0.29    1.26
1.78    2.90    1.13
40.70   NaN     NaN
51.75   NaN     NaN
3.65    1.74    0.37
2.93    1.56    1.64
3.43    NaN     NaN
2.93    NaN     NaN
10.37   NaN     NaN

How can I achieve that?

like image 443
Mono Neu Elogy Avatar asked Jan 25 '23 15:01

Mono Neu Elogy


1 Answers

Use DataFrame.mask with default value NaN for replace by mask:

df[['B','C']] = df[['B','C']].mask(df.A > 7)

Or DataFrame.loc with specify np.nan:

df.loc[df.A > 7, ['B','C']] = np.nan

print (df)
        A     B     C
0    4.43   NaN  1.11
1    3.70  0.48  0.79
2    2.78 -0.29  1.26
3    1.78  2.90  1.13
4   40.70   NaN   NaN
5   51.75   NaN   NaN
6    3.65  1.74  0.37
7    2.93  1.56  1.64
8    3.43   NaN   NaN
9    2.93   NaN   NaN
10  10.37   NaN   NaN
like image 102
jezrael Avatar answered Jan 31 '23 10:01

jezrael