Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create 2 new columns based on values separated by "-" in first column in Python Pandas?

I have Data Frame in Python Pandas like below:

col1
-------
XX - YTR
AA - BRa
Nar - Op1

Based on values in "col1" I would like to create 2 new column by separate values in "col1", so I need to have solution like below:

col1      | col2| col3
-----------------------
XX - YTR  | XX  | YTR
AA - BRa  | AA  | BRa
Nar - Op1 | Nar | Op1

How can I do that in Python Pandas ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use str.split:

df = df.join(df['col1'].str.split(' - ', expand=True) \
                       .rename(columns={0: 'col2', 1: 'col3'}))
print(df)

# Output:
        col1 col2 col3
0   XX - YTR   XX  YTR
1   AA - BRa   AA  BRa
2  Nar - Op1  Nar  Op1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading