I have a Dataframe with a column which contains integers and sometimes a string which contains multiple numbers which are comma separated (like “1234567, 89012345, 65425774”).
I want to convert that string to an integer list so it’s easier to search for specific numbers.
JavaScript
x
16
16
1
In [1]: import pandas as pd
2
3
In [2]: raw_input = "1111111111 666 10069759 9695011 9536391,2261003 9312405 15542804 15956127 8409044 9663061 7104622 3273441 3336156 15542815 15434808 3486259 8469323 7124395 15956159 3319393 15956184
4
: 15956217 13035908 3299927"
5
6
In [3]: df = pd.DataFrame({'x':raw_input.split()})
7
8
In [4]: df.head()
9
Out[4]:
10
x
11
0 1111111111
12
1 666
13
2 10069759
14
3 9695011
15
4 9536391,2261003
16
Advertisement
Answer
Since your column contains strings and integers, you want probably something like this:
JavaScript
1
8
1
def to_integers(column_value):
2
if not isinstance(column_value, int):
3
return [int(v) for v in column_value.split(',')]
4
else:
5
return column_value
6
7
df.loc[:, 'column_name'] = df.loc[:, 'column_name'].apply(to_integers)
8