Canovice
Canovice

Reputation: 10501

In pandas, convert float64 (with NaN values) to strings (with no decimals showing)

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?

Upvotes: 1

Views: 1833

Answers (2)

mozway
mozway

Reputation: 262634

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    

Upvotes: 1

jezrael
jezrael

Reputation: 863791

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)

Upvotes: 2

Related Questions