Home > Software engineering >  In pandas, convert float64 (with NaN values) to strings (with no decimals showing)
In pandas, convert float64 (with NaN values) to strings (with no decimals showing)

Time:03-03

We are trying to go from

zed = pd.DataFrame(data = {'a': [33.0, 67.0, np.nan]})

to

pd.DataFrame(data = {'a': ['33', '67', '']})

We've tried zed['a'].astype(np.int).astype(str) however this throws the error Cannot convert non-finite values (NA or inf) to integer because of the NaN value. Is it possible to go from floats to strings with no decimals, and with NaN values replaced by empty strings?

CodePudding user response:

First idea is use Int64 for integer NaNs and then set empty string:

zed['a'] = zed['a'].astype('Int64').astype(str).replace('<NA>','')
print (zed)
    a
0  33
1  67
2    

Or for old pandas version is possible this alternative:

zed['a'] = zed['a'].fillna(0).astype(int).astype(str).mask(zed['a'].isna(),'')

If need missing values insted empty strings:

zed['a'] = zed['a'].fillna(0).astype(int).astype(str).mask(zed['a'].isna())
print (zed)
     a
0   33
1   67
2  NaN

Or:

zed.loc[zed['a'].notna(), 'a'] = zed['a'].astype('Int64').astype(str)
zed['a'] = zed['a'].astype('Int64').astype(str).replace('<NA>', np.nan)

CodePudding user response:

You can handle the trimming of the decimal at the string level:

zed['b'] = zed['a'].fillna('').astype(str).str.replace(r'\..*', '', regex=True)

or:

zed['b'] = zed['a'].fillna('').astype(str).str.split('.').str[0]

or:

zed['b'] = zed['a'].map('{:.0f}'.format).replace('nan', '')

output:

      a   b
0  33.0  33
1  67.0  67
2   NaN    
  • Related