576i
576i

Reputation: 8362

In pandas, how do I convert a series of float or none to strings with integers

I'm stuck with a pandas series that's containing document numbers but have been imported as float64 values. Some are missing.

Converting the series to string adds a ".0" to each number or changes the number to e-notation.

Converting to integer causes an error message: ValueError: Cannot convert NA to integer

Example:

s = pd.Series([129944444999999922.0, 1001.0, 1119999999912.0, None])
s.astype('str')

prints

0       1.29944445e+17
1               1001.0
2    1.11999999991e+12
3                  nan
dtype: object

How can I convert the series to show the document number as just the number, no e+ notation and the nan value as an empty string?

Upvotes: 3

Views: 463

Answers (1)

jezrael
jezrael

Reputation: 862761

Use list comprehension:

s1 = pd.Series(['' if pd.isnull(x) else int(x) for x in s], index=s.index)

print (s1.apply(type))
0    <class 'int'>
1    <class 'int'>
2    <class 'int'>
3    <class 'str'>
dtype: object

print (s1.tolist())
[129944444999999920, 1001, 1119999999912, '']

Upvotes: 3

Related Questions