sharp
sharp

Reputation: 2158

Python convert list to string in the dataframe

I have bunch of list and string like texts in the cell value of the pandas data frame. I am trying to convert list to string, I am able to convert list to string, but its splitting the string as well. How do I only apply this logic if the cell contains list [] in the particular column?

raw_data = {'Name': [['\'John Smith\''], ['\'Jane Doe\'']],
        'id': [['\'A1005\'','\'A1006\''], 'A200,A400,A500']}
dfRaw = pd.DataFrame(raw_data, columns = ['Name','id'])
dfRaw['Name'] = dfRaw['Name'].astype(str)

Data

Name                    id
0   ["'John Smith'"]    ['A1005', 'A1006']
1   ["'Jane Doe'"]  A200,A400,A500

Need output like this:

    Name                id
0   ["'John Smith'"]    'A1005','A1006'
1   ["'Jane Doe'"]      A200,A400,A500

But the code below is splitting string cell values too.

dfRaw['id'] = dfRaw['id'].apply(lambda x: ','.join([str(i) for i in x]))

Name                     id
0   ["'John Smith'"]    'A1005','A1006'
1   ["'Jane Doe'"]  A,2,0,0,,,A,4,0,0,,,A,5,0,0

Upvotes: 1

Views: 2561

Answers (1)

yatu
yatu

Reputation: 88305

You could use a list comprehension to generate a new list with the rows in id joining those entries that are lists using string.join. You can check if an entry is a list using isinstance:

df['id'] = [','.join(i) if isinstance(i, list) else i for i in df['id']]

Output

       Name                    id
0  ['John Smith']          A1005,A1006
1    ['Jane Doe']        A200,A400,A500

Upvotes: 2

Related Questions