How to replace negative numbers in Pandas Data Frame by zero

前端 未结 5 853
孤独总比滥情好
孤独总比滥情好 2020-11-27 15:09

I would like to know if there is someway of replacing all DataFrame negative numbers by zeros?

5条回答
  •  一向
    一向 (楼主)
    2020-11-27 15:43

    Another clean option that I have found useful is pandas.DataFrame.mask which will "replace values where the condition is true."

    Create the DataFrame:

    In [2]: import pandas as pd
    
    In [3]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})
    
    In [4]: df
    Out[4]: 
       a  b
    0  0 -3
    1 -1  2
    2  2  1
    

    Replace negative numbers with 0:

    In [5]: df.mask(df < 0, 0)
    Out[5]: 
       a  b
    0  0  0
    1  0  2
    2  2  1
    
    

    Or, replace negative numbers with NaN, which I frequently need:

    In [7]: df.mask(df < 0)
    Out[7]: 
         a    b
    0  0.0  NaN
    1  NaN  2.0
    2  2.0  1.0
    

提交回复
热议问题