Reputation: 163
I have a dataframe like:
df = pd.DataFrame({
"from": ["'a','b'",'c','p,d'],
"to": ["m",'tom','sky'],
'other':[1,2,3]
})
I want to split each row of from
column so that each row only contains one item. How to do in a pandas way, so that I obtain as follow?
df = pd.DataFrame({
"from": ["'a'","'b'",'c','p','d'],
"to": ["m",'m','tom','sky','sky'],
'other':[1,1,2,3,3]
})
I have solved this with for
loops method. How to do it by a more pandas-style
method?
Upvotes: 1
Views: 494
Reputation: 323226
Try split
then explode
df['from'] = df['from'].str.split(',')
df = df.explode('from')
df
from to other
0 'a' m 1
0 'b' m 1
1 c tom 2
2 p sky 3
2 d sky 3
Upvotes: 2