简体   繁体   中英

Python Dataframe Convert string to list type

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]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM