Home > Blockchain >  How to convert a string type column to list type in pandas dataframe?
How to convert a string type column to list type in pandas dataframe?

Time:11-20

I have a dataframe as below,

df = pd.DataFrame({'URL_domains':[['wa.me','t.co','goo.gl','fb.com'],['tinyurl.com','bit.ly'],['test.in']]})

Here the column URL_Domains has got 2 observations with a list of Domains.

I would like to know the length of each observations URL domain list as:

df['len_of_url_list'] = df['URL_domains'].map(len)

and output as:

enter image description here

That is fine and no issues with above case and

In my case these list observations are treated string type as below:

enter image description here

When i execute the below code with string type URL domain it has shown the below output:

enter image description here

How to make a datatype conversion from string to list here in pandas ?

CodePudding user response:

Use ast.literal_eval, because eval is bad practice:

import ast

df['len_of_url_list'] = df['URL_domains'].map(ast.literal_eval)

CodePudding user response:

df["URL_domains"] = df["URL_domains"].apply(eval)
  • Related