How to convert a comma-separated value into a list of integers in a pandas dataframe?
Input:
Desired output:
CodePudding user response:
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):
df['qty'] = df['qty'].apply(lambda x: [int(y) for y in x.split(',')])
Or:
df['qty'] = df['qty'].apply(lambda x: list(map(int, x.split(','))))
Alternative solutions:
df['qty'] = [[int(y) for y in x.split(',')] for x in df['qty']]
df['qty'] = [list(map(int, x.split(','))) for x in df['qty']]
CodePudding user response:
You can use .str.split(',')
like below:
>>> df['qty'] = df['qty'].str.split(',').apply(lambda x: [int(i) for i in x])
CodePudding user response:
Or try expand=True
:
df['qty'] = df['qty'].str.split(',', expand=True).astype(int).agg(list, axis=1)
CodePudding user response:
Vectorised solution :
import ast
df["qty"] = ("[" df["qty"].astype(str) "]").apply(ast.literal_eval)