Fluxy
Fluxy

Reputation: 2978

How to convert float strings to integer strings?

I have a list of float numbers (appear as strings) and NaN values.

import numpy as np
mylist = ['1.0', '0.0', np.nan, 'a']

I need to convert float string values into integer string values, while ignoring the rest of records:

mylist = ['1', '0', np.nan, 'a']

How can I do it?

I wrote the following code, but I don't know how to handle the exceptions np.nan, a, etc.

mylist2 = []
for i in mylist:
   mylist2.append(str(int(float(n))))

Upvotes: 0

Views: 87

Answers (3)

oppressionslayer
oppressionslayer

Reputation: 7214

You can use a map that calls a function to convert them to ints:

def to_int(x):
    try:
        x = str(int(float(x)))
    except:
        pass
    return x

np.array(list(map(to_int, mylist)), dtype=object)                                                                                                                                  
# array(['1', '0', nan, 'a'], dtype=object)```

Upvotes: 1

kaya3
kaya3

Reputation: 51043

Assuming you want to just use the original values when they are not numeric strings that can be converted to integers, you can write a helper function to try doing the conversion, and return the original value if an exception is raised.

def try_int(s):
    try:
        return str(int(float(s)))
    except:
        return s

mylist2 = [try_int(s) for s in mylist]

Be aware that the conversion from a float string to an int can sometimes make the strings much longer; for example, the string '9e200' will be converted to an integer string with 201 digits.

Upvotes: 0

Hayat
Hayat

Reputation: 1639

Although there are different ways to achieve this. but let's go your way.
This might help.

 mylist2 = []
    for i in mylist:
        try:
            mylist2.append(str(int(float(n))))
        except:
            pass 

Upvotes: 0

Related Questions