1

So I have a list of string a = ['1', '2', ''] or a = ['1', '2', 'NAN'], and I want to convert it to [1, 2, 0] or [1, 2, -1] (namely NAN to -1); I used a = [int(ele) for ele in a], but got an error

ValueError: invalid literal for int() with base 10: ''

So the empty string cannot be converted automatically. Of course I could explicitly loop through the list ,but I wonder if there are more elegant/compact/efficient way.

7 Answers 7

3

Try something like this:

>> a = ['1', '2', '']
>>> def toint(s, default=0):
...     try:
...         return int(s)
...     except ValueError:
...         return default
...
>>> [toint(x) for x in a]
[1, 2, 0]
>>>

This has the added benefit of conforming to Python's Duck Typing idiom and giving you the flexibility to change the default if processing your data results in a ValueError exception. e.g:

>>> [toint(x, None) for x in a]
[1, 2, None]
Sign up to request clarification or add additional context in comments.

6 Comments

But '' should map to 0
Really? Try int("") on the Python shell.
The test case ['1', '2', ''] is supposed to map to [1, 2, 0]
@gnibbler Don't nit pick. The provided solution above is flexible enough to take a different user provided default keyword argument.
Not nit picking at all. The question clearly maps '' to 0 and 'NAN' to -1. This answer is plain wrong.
|
1

You could just write a function that makes use of int and then have a fallback condition on failures that does what you want for a input string, then call that function in the list comprehension statement.

example:

def converter(ele):
    # result = your integer conversion logic
    return result

a = [converter(ele) for ele in elements]

1 Comment

Thanks for the general idea, and I'll extend @JamesMills 's answer.
0

Use a dict to handle your unusual values

a = [int({'NAN': '-1', '': 0}.get(i, i)) for i in a] 

Comments

0

Modifying your list comprehension a little as:

a = [int(ele) if ele else 0 for ele in a]

gives what you want. This will work if the non number is a '' not if it is a NAN. If 'NAN' is part of the list, this will do it:

a = [int(ele) if ele != 'NAN' else 0 for ele in a]

4 Comments

I think you mean to say ele != 'NAN'
a = [int(ele) if ele not in 'NAN' else 0 for ele in a] on a = ['1', '2', 'NAN'] gives [1, 2, 0].
It gives the right result by accident, but the semantics are wrong. 'N', 'A', 'NA', 'AN' should cause exception, but this is masked by using in
I used it since it was going to be 'NAN' or '' as the question said. Updated. Thanks!
0
>>> a = ['1', '2', '', 'NAN']

>>> listofInt =  map(lambda s: int(s) if s not in 'NAN' else  -1 if s == 'NAN' else 0, a)

>>> print listofInt

>>> [1, 2, 0, -1]

You could write a lambda function even as a anonymous function.

Comments

0
>>> a = ['1', '2', 'NAN', '']
>>> 
>>> def to_int(value):
...     try:
...         return int(value)
...     except ValueError:
...         if value == 'NAN':
...             return -1
...         return 0
... 
>>> [to_int(x) for x in a]
[1, 2, -1, 0]
>>> 

Comments

0
def convert(myList):
    newList = [0]*len(myList)
    for i in range(len(myList)):
        try:
            newList[i] = int(myList[i])
        except:
            newList[i] = -1
    return newList

obviously this try/except just puts -1 for anything that can't be converted to an integer

easily converted to a more specific if myList[i]=='NAN': newList[i]=-1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.