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

Pandas split column in multiple columns

I have a dataframe that contains in the column "Title" the following information:

Title
2.1 text1 and bla bla 1
2.2 text2 bla 2
2.3 text3 other text 7

I tried to split the column in the following manner:

col1     Title               col3
2.1      text1 and bla bla    1
2.2      text2 bla            2
2.3      text3 other text     7

I tried to follow multiple ways but without success.

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 split on white space to obtain x. Then take the first items of lists and assign them to 'col1' and the last items to 'col3'. Finally take what’s left, join them back and assign them to 'Title':

x = df['Title'].str.split()
df['col1'] = x.str[0]
df['col3'] = x.str[-1]
df['Title'] = x.apply(lambda y: ' '.join(y[1:-1]))
df = df[['col1','Title','col3']]

Output:

  col1              Title col3
0  2.1  text1 and bla bla    1
1  2.2          text2 bla    2
2  2.3   text3 other text    7
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