简体   繁体   中英

Convert a string which is list to list

I have a data frame like

query
-----------
[]
[(apple,10),(orange,15)]
[(apple,2),(orange,5)]

python is reading this as a string instead of a list because when I do df['query'].apply(lambda x: len(x)) I get 2 instead of 0 for the first row. Is there a way to convert this to a list.

You can use apply() :

df['query'] = df['query'].apply(lambda x: x.strip('[]').split(','))

os, by list comprehension:

df['query'] = [x.strip('[]').split(',') for x in df['query']]

or, use ast.literal_eval() :

import ast
df['query'] = df['query'].apply(lambda x: ast.literal_eval(x))

or,

df['query'] = df['query'].apply(ast.literal_eval)

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