Filling a DataFrame with “sign” numbers

后端 未结 3 1766
小蘑菇
小蘑菇 2021-02-14 13:13

I have a DataFrame full of floats (positive and negative) and some NaN. I\'d like to replace every single float number with its sign:

if it\'s NaN -> it remai         


        
3条回答
  •  旧巷少年郎
    2021-02-14 13:38

    Code -

    import pandas as pd
    
    
    df = pd.DataFrame({'x' : [-5.3, 2.5, 0, float('nan')]})
    
    df['x'] = df['x'].apply(func = lambda x : x if not x else x // abs(x))
    
    print(df)
    

    Output -

        x
    0  -1
    1   1
    2   0
    3 NaN
    

提交回复
热议问题