Change pandas column values to become lists in pandas dataframe

Question:

Currently, I have

df['fruits']

apple,
orange,
pineapple,
banana,tomato,
cabbage,watermelon,

Name: fruits, Length: 5, dtype: object

How can I change the above to lists and remove the commas at the end in pandas dataframe?

Expected output of df['fruits']

[apple]
[orange]
[pineapple]
[banana,tomato]
[cabbage,watermelon]

Name: fruits, Length: 5, dtype: object

Thanks

Asked By: nerd

||

Answers:

Two options:

  1. combine rstrip and split by ,:

    df['fruits'].str.rstrip(',').str.split(',')
    
  2. or just split by , and skip the last (empty) chunk:

    df['fruits'].str.split(',').str[:-1]
    

0                  [apple]
1                 [orange]
2              [pineapple]
3         [banana, tomato]
4    [cabbage, watermelon]
Name: fruits, dtype: object
Answered By: RomanPerekhrest