user17475933
user17475933

Reputation: 55

How to remove square bracket from a dataframe column?

I have a dataframe where one column is having a list of values, how to remove the list?

Input dataframe:

enter image description here

Output should be:

enter image description here

Upvotes: 1

Views: 433

Answers (1)

jezrael
jezrael

Reputation: 862851

Use custom lambda function with if-else for join values of lists converted to strings:

df = pd.DataFrame({'Column1':['data1','data2','data3'],
                   'Column2':[['a','b','c'], 20, [14,35,50,20]]})

print (df)
  Column1           Column2
0   data1         [a, b, c]
1   data2                20
2   data3  [14, 35, 50, 20]

f = lambda x: ','.join(map(str, x)) if isinstance(x, list) else x
df['Column2'] = df['Column2'].apply(f)
print (df)
  Column1      Column2
0   data1        a,b,c
1   data2           20
2   data3  14,35,50,20

Upvotes: 3

Related Questions