Reputation: 3677
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
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
Reputation: 323396
In your case check strip
out = df.apply(lambda x : x.str.strip('[|]'))
Upvotes: 0
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