Try this:
data['q3'] = data['q3'].str.replace('[', '').replace(']','')
Answer from cteljr on Stack OverflowTry this:
data['q3'] = data['q3'].str.replace('[', '').replace(']','')
You can use the strip() as a possibility
data['q3'] = data['q3'].apply(lambda x : x.strip('[]'))
Use str.replace:
df.columns = df.columns.str.replace("[()]", "_", regex=True)
Sample:
df = pd.DataFrame({'(A)':[1,2,3],
'(B)':[4,5,6],
'C)':[7,8,9]})
print (df)
(A) (B) C)
0 1 4 7
1 2 5 8
2 3 6 9
df.columns = df.columns.str.replace(r"[()]", "_", regex=True)
print (df)
_A_ _B_ C_
0 1 4 7
1 2 5 8
2 3 6 9
Older pandas versions don't work with the accepted answer above. Something like this is needed:
df.columns = [c.replace("[()]", "_") for c in list(df.columns)]
replace looks for exact matches (by default unless you pass regex=True but you will need to escape the parentheses - see @piRSquared's answer), you want str.replace:
SF['NewPhone'] = SF['Phone'].str.replace("(",'xxx')
which will replace all occurrences of the passed in string with the new string
Example:
In[20]:
df = pd.DataFrame({'phone':['(999)-63266654']})
df
Out[20]:
phone
0 (999)-63266654
In[21]:
df['phone'].str.replace("(",'xxx')
Out[21]:
0 xxx999)-63266654
Name: phone, dtype: object
If we try replace then no match occurs:
In[22]:
df['phone'].replace("(",'xxx')
Out[22]:
0 (999)-63266654
Name: phone, dtype: object
See @piRSquared's answer for how to get replace to work as expected (I don't want to cannibalise his answer)
The Series.replace method takes a regex argument that is False by default. Set it to True. Also, if the string to be replaced is interpreted as a regex pattern, we'll need to escape the opening parenthesis.
df.phone.replace("\(", 'xxx', regex=True)
0 xxx999)-63266654
Name: phone, dtype: object
Setup from @EdChum
df = pd.DataFrame({'phone':['(999)-63266654']})