python 3.x – How to remove square brackets from entire dataframe if not every row and column have square brackets? – Code Utility

[

I have df that looks like this (with many more columns):

col1   col2    col3
[1]     4 
[2]     5      [6]
[3]

How do I remove all square brackets from the df if not every row and column have square brackets and the dataframe is too big to specify column by column ?

I can remove the brackets using this line of code, but the dataframe has to many columns:

df['col1].str.get(0)

df['col1].apply(lambda x: x.replace ('[','').replace(']','')

New df should look like this:

col1   col2    col3
  1     4 
  2     5       6
  3

,

You can cast your df to str, replace the brackets and then cast back to float:

df.astype(str).replace({"\[":"", "\]":""}, regex=True).astype(float)

,

You could use applymap to apply your function to each cell, although you would want to be a bit careful about types. For example:

df.applymap(lambda x: x.replace('[','').replace(']','') if isinstance(x, str) else x)

Produces:

  col1  col2  col3
0    1   4.0  None
1    2   5.0     6
2    3   NaN  None

,

In your case check strip

out = df.apply(lambda x : x.str.strip('[|]'))

]