Split dividers of multiple dividers into multiple columns

I have a file with 9 columns. One of the columns contains a row

Unique
3:107912234-107912321(-)
4:107913333-107913322(+)
Y:222002110-221002100(+)
MT:34330044-343123232(-)
X:838377373-834121212(+)

~ 400,000 lines with different lines. How can I split it into 4 different columns in the same df, I can use df.str(",")if there was only one separator, but since it has different separators, I get lost.

expected output:

chr  start  end  strand
3    107912234 107912321 -
4    107913333 107913322 + 
Y    222002110 221002100 + 
MT   34330044  343123232 -
X    838377373 834121212 +
+4
source share
2 answers

You can use extract:

df1 = df['Unique'].str.extract("(?P<ch>.*?):(?P<start>\d+)-(?P<end>\d+)\((?P<strand>[-+])", 
                               expand=True)
print (df1)
   ch      start        end strand
0   3  107912234  107912321      -
1   4  107913333  107913322      +
2   Y  222002110  221002100      +
3  MT   34330044  343123232      -
4   X  838377373  834121212      +

Thanks A-Za-z for the suggestion - if the data is not always +-in the column strand:

df1 = df['Unique'].str.extract("(?P<ch>.*?):(?P<start>\d+)-(?P<end>\d+)\((?P<strand>.*)\)", 
                              expand=True)
print (df1)
   ch      start        end strand
0   3  107912234  107912321      -
1   4  107913333  107913322      +
2   Y  222002110  221002100      +
3  MT   34330044  343123232      -
4   X  838377373  834121212      +

If you need to add to the original df, in this column use join:

print (df.join(df1))
                     Unique  ch      start        end strand
0  3:107912234-107912321(-)   3  107912234  107912321      -
1  4:107913333-107913322(+)   4  107913333  107913322      +
2  Y:222002110-221002100(+)   Y  222002110  221002100      +
3  MT:34330044-343123232(-)  MT   34330044  343123232      -
4  X:838377373-834121212(+)   X  838377373  834121212      +
+5

, regex, df

import re

x ='X:838377373-834121212(-)'
[s for s in re.split('\-(?=[0-9])|:|\(|\)', x) if s]
+1

Source: https://habr.com/ru/post/1676255/


All Articles