I have the following main dataframe:
first.seqnames first.start first.end first.width first.strand second.seqnames second.start second.end second.width second.strand
0 chr1 346212 346975 7 * chr1 10882 10888 7 *
1 chr1 3135476 3136100 2 * chr1 10890 10891 2 *
2 chr1 11473 11484 12 * chr1 10893 10904 12 *
3 chr1 5388140 5388730 2 * chr1 11096 11097 2 *
4 chr1 346213 346984 68 * chr1 11202 11269 68 *
I want to return the rows of above dataframe that don't exist within the range of the following dataframe:
first.seqnames first.start first.end 3 4 5
3503 chr1 346213 346984 . 0 .
3504 chr1 3135466 3136202 . 0 .
3505 chr1 3190760 3191377 . 0 .
3506 chr1 3354604 3355258 . 0 .
3507 chr1 5388136 5388749 . 0 .
Here, the first dataframe's 'first.start' and 'first.end' should not exist within the range(346213, 346984),.......
I've tried the following code which creates memory and time complexity. Even the result isn't accurate. Here, some of the df1 ranges exist exactly between the df2 ranges and some overlaps. In case of overlaps, the ranges can be ignored.
def range_subset(range1, range2):
"""Whether range1 is a subset of range2."""
if not range1:
return True # empty range is subset of anything
if not range2:
return False # non-empty range can't be subset of empty range
if len(range1) > 1 and range1.step % range2.step:
return False # must have a single value or integer multiple step
return range1.start in range2 and range1[-1] in range2
for a,b in zip(df1['first.start'], df1['first.end']):
for i,j in zip(df2['first.start'], df2['first.end']):
if(range_subset(range(a, b), range(i, j)) == True):
print(a,b)
Output:
first.seqnames first.start first.end first.width first.strand second.seqnames second.start second.end second.width second.strand
0 chr1 346212 346975 7 * chr1 10882 10888 7 *
2 chr1 11473 11484 12 * chr1 10893 10904 12 *
source https://stackoverflow.com/questions/71227508/return-the-range-of-a-dataframe-not-within-a-range-of-another-dataframe
Comments
Post a Comment