0

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))))
5
  • 2
    Well, what do you want to happen for NaN or infinity, or non-integer strings? Commented Dec 15, 2019 at 18:53
  • What is this for? Seems slightly odd, no? Commented Dec 15, 2019 at 18:54
  • @kaya3 He said he want to ignore rest of the record. Commented Dec 15, 2019 at 18:58
  • But what does "ignore" mean? Leave them as is, remove them, something else? Commented Dec 15, 2019 at 18:58
  • How did you get the data? Can you fix it before you create the array? Commented Dec 15, 2019 at 19:03

3 Answers 3

1

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)```
Sign up to request clarification or add additional context in comments.

Comments

0

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 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.