Reputation: 4604
I have a CSV file coming from the field. It has the data in a peculiar format. That is, a list of values in string format. I want to convert it to the list type
My code:
df = pd.DataFrame({'x':['-1,0,1,2,10','1.5,2,4,5'],'y':['2.5,2.4,2.3,1.5,0.1','5,4.5,3,-0.1']})
df =
x y
0 '-1, 0, 1, 2, 10' '2.5, 2.4, 2.3, 1.5, 0.1'
1 '1.5, 2, 4, 5' '5, 4.5, 3, -0.1'
Expected answer:
df =
x y
0 [-1, 0, 1, 2, 10] [2.5, 2.4, 2.3, 1.5, 0.1]
1 [1.5, 2, 4, 5] [5, 4.5, 3, -0.1]
Upvotes: 0
Views: 216
Reputation: 71707
applymap
with ast.literal_eval
would be the fastest option
import ast
df.applymap(ast.literal_eval)
Note this will produce tuples in output, although it doesn't matter but if you specifically need lists in your output then we can chain another applymap
df.applymap(ast.literal_eval).applymap(list)
x y
0 [-1, 0, 1, 2, 10] [2.5, 2.4, 2.3, 1.5, 0.1]
1 [1.5, 2, 4, 5] [5, 4.5, 3, -0.1]
Upvotes: 1