Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas drop multiple in range value using isin

Given a df

     a
0    1
1    2
2    1
3    7
4   10
5   11
6   21
7   22
8   26
9   51
10  56
11  83
12  82
13  85
14  90

I would like to drop rows if the value in column a is not within these multiple range
(10-15),(25-30),(50-55), (80-85). Such that these range are made from the ‘lbotandltop`

lbot =[10, 25, 50, 80]
ltop=[15, 30, 55, 85]

I am thinking this can be achieve via pandas isin

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df[df['a'].isin(list(zip(lbot,ltop)))]

But, it return empty df instead.

The expected output is

a
10
11
26
51
83
82
85

>Solution :

Create values in flatten list comprehension with range:

df = df[df['a'].isin([z for x, y in zip(lbot,ltop) for z in range(x, y+1)])]
print (df)
     a
4   10
5   11
8   26
9   51
11  83
12  82
13  85

Or use np.concatenate for flatten list of ranges:

df = df[df['a'].isin(np.concatenate([range(x, y+1) for x, y in zip(lbot,ltop)]))]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading