Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I am trying to split a column in a dataframe in python. It looks like this

col_name
UO1
UO1,UO2,UO3
UO1,UO2,UO3,UO4,UO5
UO1,SO1,SO3
SO3,UO1

I am not sure how to split them as row values. I am new to python programming

1 Answer

0 votes
by (41.4k points)

For splitting a column with multiple values in python, try the below code:

df['id'] = df.index+1

df.set_index('id').col_name.str.split(',', expand = True).stack().reset_index(1, drop = True).reset_index(name = 'symptoms')


 

    id  symptoms

0   1 UO1

1   2 UO1

2   2 UO2

3   2 UO3

4   3 UO1

5   3 UO2

6   3 UO3

7   3 UO4

8   3 UO5

9   4 UO1

10  4 SO1

11  4 SO3

12  5 SO3

13  5 UO1

Browse Categories

...