close

How to remove square bracket from pandas dataframe

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to remove square bracket from pandas dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to remove square bracket from pandas dataframe?

  1. How to remove square bracket from pandas dataframe?

    If values in column value have type list, use:
    df['value'] = df['value'].str[0]

  2. remove square bracket from pandas dataframe

    If values in column value have type list, use:
    df['value'] = df['value'].str[0]

Method 1

If values in column value have type list, use:

df['value'] = df['value'].str[0]

Or:

df['value'] = df['value'].str.get(0)

Sample:

df = pd.DataFrame({'value':[[63],[65],[64]]})
print (df)
  value
0  [63]
1  [65]
2  [64]

#check type if index 0 exist
print (type(df.loc[0, 'value']))
<class 'list'>

#check type generally, index can be `DatetimeIndex`, `FloatIndex`...
print (type(df.loc[df.index[0], 'value']))
<class 'list'>

df['value'] = df['value'].str.get(0)
print (df)
   value
0     63
1     65
2     64

If strings use str.strip and then convert to numeric by astype:

df['value'] = df['value'].str.strip('[]').astype(int)

Sample:

df = pd.DataFrame({'value':['[63]','[65]','[64]']})
print (df)
  value
0  [63]
1  [65]
2  [64]

#check type if index 0 exist
print (type(df.loc[0, 'value']))
<class 'str'>

#check type generally, index can be `DatetimeIndex`, `FloatIndex`...
print (type(df.loc[df.index[0], 'value']))
<class 'str'>


df['value'] = df['value'].str.strip('[]').astype(int)
print (df)
  value
0    63
1    65
2    64

Method 2

if string we can also use string.replace method

import pandas as pd

df =pd.DataFrame({'value':['[63]','[65]','[64]']})

print(df)
  value
0  [63]
1  [65]
2  [64]

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

#convert the string columns to int
df['value'] = df['value'].astype(int)

#output
print(df)

   value
0     63
1     65
2     64

print(df.dtypes)
value    int32
dtype: object

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read