Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading