Python Pandas Dataframe Column of Lists, convert list to string in new column -


i have dataframe column of lists can created with:

import pandas 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 create new column called 'liststring' takes every element of each list in lists , creates string each element separated commas. elements of each list can int, float, or string. result 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 converting panda df list string:

df['liststring']=df.lists.apply(lambda x: ', '.join(str(x))) 

but unfortunately result takes every character , seperates 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 help!

try df.apply ','.join. need convert list items strings first, that's map comes in handy.

in [684]: df['liststring'] = df['lists'].apply(lambda x: ','.join(map(str, x))); df out[684]:                  lists    liststring 0  [1, 2, 12, 6, abc]  1,2,12,6,abc 1     [1000, 4, z, a]    1000,4,z,a 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -