I have a dataframe with a column of lists which can be created with:
import pandas as pd
lists={1:[[1,2,12,6,'ABC']],2:[[1000,4,'z','a']]}
#create test dataframe
df=pd.DataFrame.from_dict(lists,orient='index')
df=df.rename(columns={0:'lists'})
The dataframe df
looks like:
lists
1 [1, 2, 12, 6, ABC]
2 [1000, 4, z, a]
I need to create a new column called 'liststring
' which takes every element of each list in lists
and creates a string with each element separated by commas. The elements of each list can be int
, float
, or string
. So the result would be:
lists liststring
1 [1, 2, 12, 6, ABC] 1,2,12,6,ABC
2 [1000, 4, z, a] 1000,4,z,a
I have tried various things, including from Converting a Panda DF List into a string:
df['liststring']=df.lists.apply(lambda x: ', '.join(str(x)))
but unfortunately the result takes every character and seperates by comma:
lists liststring
1 [1, 2, 12, 6, ABC] [, 1, ,, , 2, ,, , 1, 2, ,, , 6, ,, , ', A...
2 [1000, 4, z, a] [, 1, 0, 0, 0, ,, , 4, ,, , ', z, ', ,, , '...
Thanks in advance for the help!
See Question&Answers more detail:
os