2

I have an array x and one of the values is NaN.

x = [1, 2, NaN, 3, 5]

All the elements are integer excepting NaN. This array type is regarded as float64 not int.

I would like to convert type from floating to string.

I tried astype(str). But this make decimal point such as x = [1.0, 2.0, NaN, 3.0, 5.0]

I tried astype(int).astype(str). However, in this case, it doesn't work due to NaN element.

So, how I can convert integer array with some of element are NaN to string type without decimal point?

Thank you for reading.

import numpy as np
import pandas as pd

df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})

# df.dtypes

df['x'] = df['x'].astype(str)
# In this case, it make decimal point.

df['x'] = df['x'].astype(int).astype(str)
# It doesn't work due to NaN element.
jdaz
  • 5,964
  • 2
  • 22
  • 34
user3685918
  • 335
  • 2
  • 12

4 Answers4

4
import numpy as np
df1 = df.replace(np.nan, '', regex=True)

This might help. It will replace all NaNs with an empty string.

Asiri Hewage
  • 577
  • 3
  • 16
0

You can filter out Nans rather than replacing with ''

filtered_df = df[df['x'].notnull()]

Source: Python pandas Filtering out nan from a data selection of a column of strings

Codigo Morsa
  • 820
  • 7
  • 14
0

Instead of worrying about the nan, you can use this to make sure it doesnt impact your operations atall.

df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})
df = df.convert_dtypes()

This let you work with Nans without pandas changing dtypes automatically and it will keep the items in the list as ints.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0
import pandas as pd
import numpy as np
​
df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})
df.replace(np.nan,"nan",inplace=True)
df = pd.DataFrame(map(str,df['x'])

Might not be the most elegant solution but gets the job done. You might need to use a for loop if you have multiple columns.

the__hat_guy
  • 133
  • 8