Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a list in rows of dataframe in one column to simple string

Tags:

python

pandas

I have a dataframe which has list in one column that I want to convert into a simple string

    id          data_words_nostops
    26561364    [andrographolide, major, labdane, diterpenoid]
    26561979    [dgat, plays, critical, role, hepatic, triglyc]
    26562217    [despite, success, imatinib, inhibiting, bcr] 

DESIRED OUTPUT

id          data_words_nostops
26561364    andrographolide, major, labdane, diterpenoid
26561979    dgat, plays, critical, role, hepatic, triglyc
26562217    despite, success, imatinib, inhibiting, bcr
like image 465
Khaned Avatar asked Mar 03 '23 03:03

Khaned


1 Answers

Try this :

df['data_words_nostops'] = df['data_words_nostops'].apply(lambda row : ','.join(row))

Complete code :

import pandas as pd
l1 = ['26561364', '26561979', '26562217']
l2 = [['andrographolide', 'major', 'labdane', 'diterpenoid'],['dgat', 'plays', 'critical', 'role', 'hepatic', 'triglyc'],['despite', 'success', 'imatinib', 'inhibiting', 'bcr']]


df = pd.DataFrame(list(zip(l1, l2)), 
               columns =['id', 'data_words_nostops'])
df['data_words_nostops'] = df['data_words_nostops'].apply(lambda row : ','.join(row))

Output :

id  data_words_nostops
0   26561364    andrographolide,major,labdane,diterpenoid
1   26561979    dgat,plays,critical,role,hepatic,triglyc
2   26562217    despite,success,imatinib,inhibiting,bcr
like image 185
Suraj Subramanian Avatar answered May 01 '23 20:05

Suraj Subramanian