Back
I am trying to split a column in a dataframe in python. It looks like this
col_nameUO1UO1,UO2,UO3UO1,UO2,UO3,UO4,UO5UO1,SO1,SO3SO3,UO1
I am not sure how to split them as row values. I am new to python programming
For splitting a column with multiple values in python, try the below code:
df['id'] = df.index+1df.set_index('id').col_name.str.split(',', expand = True).stack().reset_index(1, drop = True).reset_index(name = 'symptoms') id symptoms0 1 UO11 2 UO12 2 UO23 2 UO34 3 UO15 3 UO26 3 UO37 3 UO48 3 UO59 4 UO110 4 SO111 4 SO312 5 SO313 5 UO1
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
31k questions
32.8k answers
501 comments
693 users