Home > Software engineering >  Split string into 2 columns, but keep the separator
Split string into 2 columns, but keep the separator

Time:10-05

I have a column in a panda df I want to split into 2 columns. The separator is a word ( actually a list of words) The problem is that I want to keep the separator (word)

My current code looks like:

new_auditlog = auditlog['Description'].str.split("Modified| Reset | Rebooted | Created | Disabled",1, expand = True )
                auditlog["Action"] = new_auditlog[0]
                auditlog["Something"] = new_auditlog[1]
                auditlog.drop(columns=["Description"], inplace= True)

The column looks like enter image description here

This should be split into 2 columns based on the separator

Problem is that the separator word is "lost, and it looks like: enter image description here

It's possible to keep the separator in a normal string split. But can you do the same in a panda dataframe to columns?

CodePudding user response:

you can add the () to keep the separators, for example:

df['column1'].str.split('(sep1|sep2|sep3)')
  • Related