Home > Software engineering >  Remove single quote from list of strings in pandas dataframe
Remove single quote from list of strings in pandas dataframe

Time:06-29

I have a pandas dataframe that looks like the following. I want to get rid of the single quotes of the strings in the list. Any suggestion is appreciated.

    name      relations
0   mary      ['andrew', 'jane']
1   jack      ['priscilla', 'mary']
2   jason     ['howard', 'jackie']

Expected output

    name      relations
0   mary      [andrew, jane]
1   jack      [priscilla, mary]
2   jason     [howard, jackie]

CodePudding user response:

The string becomes an object and displays an error if is not defined. But it should do what you need.

df['relations'] = df['relations'].apply(lambda x: list(map(eval,x)))

CodePudding user response:

The main reason I faced this issue was that my lists were stored as string in the dataframe.

When doing

for i, l in enumerate(df[0]):
    print("list",i,"is",type(l))

My output is

list 0 is <class 'str'>
list 1 is <class 'str'>
list 2 is <class 'str'>

When I perform the following code -

df['relations'] = df['relations'].apply(eval)

I get a list back, and it is now correct.

Output of

for i, l in enumerate(df[0]):
    print("list",i,"is",type(l))

Give me

list 0 is <class 'list'>
list 1 is <class 'list'>
list 2 is <class 'list'>

Doing a df again would essentially get what I wanted -> without the single quote in the list

name          relations
0   mary      [andrew, jane]
1   jack      [priscilla, mary]
2   jason     [howard, jackie]

  • Related