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
Answers:
Two options:
-
combine rstrip
and split
by ,
:
df['fruits'].str.rstrip(',').str.split(',')
-
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
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
Two options:
-
combine
rstrip
andsplit
by,
:df['fruits'].str.rstrip(',').str.split(',')
-
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