0

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]
1
  • Use str.split: df.apply(lambda x: x.str.split(', ')) Commented Jul 20, 2021 at 17:56

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.