0

I am working on splitting a column in the dataframe, the column has similar words but only the last few words are different. I am trying to split the common words in one column and the words that are different is another column.

This is how the dataframe looks like.

**Column1** InitialCharms::Charm::AAAAAA InitialCharms::Charm::BBBBBB InitialCharms::Charm::CCCCCC InitialCharms::Charm::DDDDDD InitialCharms::Charm::EEEEEE InitialCharms::Charm::FFFFFF InitialCharms::Charm::GGGGGG InitialCharms::Charm::HHHHHH InitialCharms::Charm::IIIIII InitialCharms::Charm::JJJJJJ InitialCharms::Charm::KKKKKK InitialCharms::Charm::LLLLLL The Expected output: **Column1** **Column2** InitialCharms AAAAA InitialCharms BBBBB InitialCharms CCCCC 

I am using pandas!

2
  • What about ::Charm::?? Commented May 8, 2019 at 13:12
  • @yatu Thanks yes it's working I a was initially using "::" and I wasn't able to figure the way to split the column. Both jezrael and Pasindu Gamarachchi solution works. Commented May 8, 2019 at 13:26

2 Answers 2

3

Use Series.str.split and if necessary remove second column by drop:

df1 = df['Column1'].str.split('::', expand=True).drop(1, axis=1) 

Or:

df1 = df['Column1'].str.split('::Charm::', expand=True) 

df1.columns = ['Col1','Col2'] print (df1) Col1 Col2 0 InitialCharms AAAAAA 1 InitialCharms BBBBBB 2 InitialCharms CCCCCC 3 InitialCharms DDDDDD 4 InitialCharms EEEEEE 5 InitialCharms FFFFFF 6 InitialCharms GGGGGG 7 InitialCharms HHHHHH 8 InitialCharms IIIIII 9 InitialCharms JJJJJJ 10 InitialCharms KKKKKK 11 InitialCharms LLLLLL 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot it's working, I am new to python and pandas.
2

Try this

df['NewColumn1'] = df['Column1'].str.split('::').str[0] df['NewColumn2'] = df['Column1'].str.split('::').str[-1] 

1 Comment

I don't think you should split twice. You can save the intermediate result to avoid duplicating the computation. I.e., u = df['Column1'].str.split('::'); u.str[0]; u.str[-1]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.