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 split the pandas column into two

import pandas as pd
df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [(2, 1), (2, 2), (3, 3)]})

I have dataframe above. I wish to split the column col2 such as below:

import pandas as pd
df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [2, 2, 3], 'col3': [1, 2, 3]})

Is it possible?

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 :

You can use to_list and 2D assignment:

df[['col2', 'col3']] = df['col2'].tolist()

output:

   col1  col2  col3
0  asdf     2     1
1    xy     2     2
2     q     3     3

Or, if you want to remove ‘col2’ and assign to another name, using pop:

df[['col3', 'col4']] = df.pop('col2').tolist()

output:

   col1  col3  col4
0  asdf     2     1
1    xy     2     2
2     q     3     3
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