How to remove square bracket from pandas dataframe
If values in column value
have type list
, use:
df['value'] = df['value'].str[0]
Or:
df['value'] = df['value'].str.get(0)
Docs.
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
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