Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python or pandas split columns by comma and append into rows

I have a dataset looks like this: 1

I want to split the second column and then append the values like this using python or pandas:

2

How could I change it? Thanks

like image 890
C Cheng Avatar asked Aug 29 '26 05:08

C Cheng


1 Answers

You can make use of explode

df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': ['ab,s', 'a,s,d,f', 'rk,lw', 'get,me']})

# Split by each comma
df.B = df.B.str.split(',')
df.explode('B')
like image 111
mnist Avatar answered Aug 31 '26 22:08

mnist



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!