简体   繁体   中英

Extract string between two delimiters in Python dataframe

I am trying to extract values between : and - from this below

>>> all_cancers.iloc[:,3]
0        chr1:100414771-100414772
1          chr1:10506157-10506158
2        chr1:109655506-109655507
3        chr1:113903257-113903258
4        chr1:117598869-117598870

I tried re.findall('\:(.*?)\-', all_cancers.iloc[:,3].astype(str)) to do this but it generates the following error: TypeError: expected string or bytes-like object .

What is missing here?

You can use this pattern,

In [33]: re.match(r'.*:(.*)-',"chr1:100414771-100414772").group(1)
Out[33]: '100414771'

In datafame you can do with apply + lambda

all_cancers.iloc[:,3].apply(lambda x: re.match(r'.*:(.*)-', x).group(1))

Using extract

all_cancers.iloc[:,3].str.extract(r'.*:(.*)-')

(credit: OlvinRoght's comment)

Debuggex Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM