1

I have the following dataframe:

d = {'col1':['a','b','c'],'col2':['x1;x2;x3','x5','x6'],'col3':['y1','y2,y3,y4','y5']}
df = pd.DataFrame(d)

I want to choose a column and split that into multiple rows, for instance if I choose col2 I expect the result to be the output of the following:

d = {'col1':['a','a','a','b','c'],'col2':['x1','x2','x3','x5','x6'],'col3':['y1','y1','y1','y2,y3,y4','y5']}
df = pd.DataFrame(d)

and if I choose col3 I expect:

d = {'col1':['a','b','b','b','c'],'col2':['x1;x2;x3','x5','x5','x5','x6'],'col3':['y1','y2','y3','y4','y5']}
df = pd.DataFrame(d)

Note that in col2, x are separated by ; while in col3, y are separated by ,. I have tried .explode but that did not give the results I've shown above.

1 Answer 1

3
df=df.replace(regex=r'[^\w]',value=',')#replace any punctuation with comma
df=df.assign(col2=df['col2'].str.split(',')).explode('col2')#Explode column2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.