Reputation: 1293
I have a DataFrame that has data in the below format:
name,type
P1,["prod_1", "prod_3"]
P2,["prod_2", "prod_3"]
P3,None
I am trying to convert this such that I get the below output:
name,type
P1,"prod_1", "prod_3"
P2,"prod_2", "prod_3"
P3,None
The data type of df['type']
is object
I tried to use regular expression as below:
df['type'] = df['type'].replace("[", df['type'])
df['type'] = df['type'].replace("]", df['type'])
But this still returns the same output with the brackets before and after
Upvotes: 0
Views: 1846
Reputation: 11192
use this,
df['type']=df['type'].str.replace('\[|\]','')
O/P:
name type
0 P1 'prod_1', 'prod_3'
1 P2 'prod_2', 'prod_3'
2 P3 None
Docs:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html
str.replace
receives regex as replacement pattern, |
used here as or
and \
escape character used here to differentiate from regex character
As @ Jon Clements suggests strip
would be the best choice for this problem.
df['type'] = df['type'].str.strip('[]')
Upvotes: 3