RustyShackleford
RustyShackleford

Reputation: 3677

How to remove square brackets from entire dataframe if not every row and column have square brackets?

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

Upvotes: 0

Views: 1850

Answers (3)

Henry Yik
Henry Yik

Reputation: 22523

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

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

Upvotes: 2

BENY
BENY

Reputation: 323396

In your case check strip

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

Upvotes: 0

Matti John
Matti John

Reputation: 20537

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

Upvotes: 0

Related Questions