How to convert a comma-separated value into a list of integers in a pandas dataframe?
Input:
Desired output:
Advertisement
Answer
There are 2 steps – split
and convert to integers, because after split values are lists of strings, solution working well also if different lengths of lists (not added None
s):
JavaScript
x
2
1
df['qty'] = df['qty'].apply(lambda x: [int(y) for y in x.split(',')])
2
Or:
JavaScript
1
2
1
df['qty'] = df['qty'].apply(lambda x: list(map(int, x.split(','))))
2
Alternative solutions:
JavaScript
1
3
1
df['qty'] = [[int(y) for y in x.split(',')] for x in df['qty']]
2
df['qty'] = [list(map(int, x.split(','))) for x in df['qty']]
3