Brett
Brett

Reputation: 12017

Splitting a comma separated value into separate rows in Pandas

I have a csv that has the data (as a Pandas dataframe):

Col1    Col2    Col3
1       0.034   0.1
2,3,4   1.234   0.2
5       0.3     1.3

And I am trying to find a way to "expand" that second entry into multiple (three, in this example) lines. The final dataframe I am trying to achieve looks like:

Col1    Col2    Col3
1       0.034   0.1
2       1.234   0.2
3       1.234   0.2
4       1.234   0.2
5       0.3     1.3

Does Pandas have any build in ways to do this? Or am I left to resorting to creating a new dataframe and looping over the multivalued rows?

Upvotes: 1

Views: 2971

Answers (1)

fsl
fsl

Reputation: 3280

Here is one way using explode:

df.Col1 = df.Col1.str.split(',')                                                               
df.explode('Col1')

Output:

  Col1   Col2  Col3
0    1  0.034   0.1
1    2  1.234   0.2
1    3  1.234   0.2
1    4  1.234   0.2
2    5  0.300   1.3

Upvotes: 3

Related Questions