How I can use replace and then make new rows in pandas?

Viewed 32

I each row of my data frame I have a couple of words. they has been separated by , . I want remove , if there is a space after that in all rows. and then make new row where I have ,.

For example let I have:

title               id
A, home,sad, Kar    1
car,figth, Sumer    2
light,daad,Hi       3

There is space after , in the first row after A also after sad . in the second row after figth. and the last row is good. so I will make new row with rest and will keep their id.

title               id
A home              1
sad Kar             1
car,                2
figth Sumer         2
light               3
 daad              3
 Hi                3
 park              3
2 Answers

Let us try str.replace + str.split followed by explode:

df.assign(title=df['title'].str.replace(r',\s', ' ').str.split(',')).explode('title')

         title  id
0       A home   1
0      sad Kar   1
1          car   2
1  figth Sumer   2
2        light   3
2         daad   3
2           Hi   3

Try with positive look forward:

df.assign(title=df.title.str.split(',(?=\S)')).explode('title')

Output:

          title  id
0       A, home   1
0      sad, Kar   1
1           car   2
1  figth, Sumer   2
2         light   3
2          daad   3
2            Hi   3
Related