'converting string to int: Python

I have a Series Dataobject which have dtype as object. It contains int in str format as well as many strings. I want to convert only int to int type and del rest.

Example:

'1','3','sd34','4','r5'

Result:

[1, 3, 4]


Solution 1:[1]

Here's a simple one-liner.

output = [int(s) for s in data_list if s.isdecimal()]

You may also use a generator expression in case the dataset is large. This will be much more memory efficient for a single iteration over the data.

output_gen = (int(s) for s in data_list if s.isdecimal())

Last option, if you wish to be extremely efficient, is to use full C-level iterators:

output_gen = map(int, filter(str.isdecimal, data_list))

Solution 2:[2]

data = ['1','3','sd34','4','r5']
result = []

for d in data:
    try:
        result.append(int(d))
    except:
        pass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ForceBru