Home > Blockchain >  Python: remove brackets of list elements while printing pandas dataframe
Python: remove brackets of list elements while printing pandas dataframe

Time:02-14

I have a pandas dataframe of this kind

d = {'col1': [1, [2,3]], 'col2': [[3,4,5], 4]}
d = pd.DataFrame(d)
print(d)

output:

     col1       col2
0       1  [3, 4, 5]
1  [2, 3]          4

what is the best way to remove the brackets of all the list elements while printing this dataframe?

CodePudding user response:

you can simply convert the column (list) to string and remove the brackets, such that:

for c in d.columns:
    d[c]= d.apply(lambda x: str(x[c]).replace("[",'').replace(']',''), axis=1)

desired result

    col1    col2
0   1       3, 4, 5
1   2, 3    4

CodePudding user response:

The very same idea as @adhg’s answer but we could also do:

df = d.astype(str).apply(lambda col: col.str.strip('[]'))

CodePudding user response:

Another way to do it:

d.applymap(lambda x: str(x)[1:-1] if type(x)==list else x)
# Out:
#    col1     col2
# 0     1  3, 4, 5
# 1  2, 3        4
  • Related