Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split pandas column into two

There are other similar questions, but the difference here is that my dataframe already has a lot of columns, only one of which needs to be split.

I have a large dataframe(hundreds of columns, millions of rows). I would like to split one of these columns when a character ("|") is found in the string.

All values have only one "|".

For a fixed length I would do this: df['StateInitial'] = df['state'].str[:2]

I wish I could replace the 2 by string.index("|"), but how do I call the string?

like image 893
Alexis Eggermont Avatar asked Aug 27 '26 07:08

Alexis Eggermont


1 Answers

How about:

df = pd.DataFrame(['a|b', 'c|d'])
s = df[0].apply(lambda x: x.split('|'))
df['left'] = s.apply(lambda x: x[0])
df['right'] = s.apply(lambda x: x[1])

Output:

     0 left right
0  a|b    a     b
1  c|d    c     d
like image 108
santon Avatar answered Aug 28 '26 20:08

santon



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!