Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a column with multiple values in python

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

like image 512
arun antony Avatar asked Mar 17 '26 02:03

arun antony


1 Answers

Try

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
like image 150
Vaishali Avatar answered Mar 21 '26 18:03

Vaishali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!