pythonpandasdataframeright-align

check text is right align or not in python


I have a dataframe like this:

  |number  |
1 |122     |
2 |345     | 
3 |     456|
4 |     789|

I want to change it into:

  |number|
1 |nan|
2 |nan| 
3 |456|
4 |789|

i want only right align value


Solution

  • I think you need test Series.str.endswith if space, then replace to NaN by Series.mask, remove possible traling spaces by Series.str.strip and convert to floats:

    df['number'] = df['number'].mask(df['number'].str.endswith(' ')).str.strip().astype(float)
    

    Or:

    df['number'] = df['number'].mask(df['number'].str[-1] == ' ').str.strip().astype(float)
    
    print (df)
       number
    1     NaN
    2     NaN
    3   456.0
    4   789.0
    

    If want integers it is possible by integer na working in pandas 0.24+:

    m = df['number'].str.endswith(' ')
    df['number'] = df['number'].mask(m).str.strip().astype(float).astype('Int64')
    
    print (df)
       number
    1     NaN
    2     NaN
    3     456
    4     789