Ahmad Mahmood
Ahmad Mahmood

Reputation: 35

Pandas DataFrames add square brackets to specific column values

how to add sqaure backets to specif column values.

like in DataFrame if I have 2 columns

  1. Name

  2. country

    Name               country
    
    Ali                UK,USA
    Sara               UK,Canada
    Tom                Australia,Canada
    

how I can add the square brackets to the values of column country.

Like:

       Name               country

   Ali                [UK,USA]
   Sara               [UK,Canada]
   Tom                [Australia,Canada]

Upvotes: 2

Views: 2747

Answers (1)

jezrael
jezrael

Reputation: 862901

Use Series.str.split for convert strings to lists:

df['country'] = df['country'].str.split(',')

If no missing values also working:

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

Upvotes: 2

Related Questions