Home > Blockchain >  How to split string using multiple characters in Pandas?
How to split string using multiple characters in Pandas?

Time:08-30

I am using Pandas and I would like to split the following strings:

pd.DataFrame(data = ['String1 - String2',
                     'This > That',
                     'One <-> Two'], columns = ["Value"])
Index Value
0 String1 - String2
1 String1 > String2
2 One <-> Two

The string splitter could be - or >. How could I split the string such that I would get the following result:

Index Value String1 String2
0 String1 - String2 String1 String2
1 This > That This That
2 One <-> Two One Two

Thanks in advance

CodePudding user response:

Use Series.str.split with regex \s for spaces before separators - or >:

df[['String1','String2']] = df['Value'].str.split('\s [->]\s ', expand=True)
print (df)
               Value  String1  String2
0  String1 - String2  String1  String2
1        This > That     This     That
  • Related