简体   繁体   中英

how to check if list of values are in range of values present in two columns?

I am new to python and still learning. I have some values which I want to check if any of them are within certain ranges. ranges are placed in two columns in a df table, so basically I want to go over the table row by row and check if any of the values are in range and count them

columnA  columnB   Counts
1           
6           10
11          15
16          20

and the numbers are in a list

list = [1,2,3,6,7,12,19]

Final output:

columnA  columnB   Counts
1            5      3
6           10      1
11          15      1
16          20      1

what I thought about is

counts=[]
for i in list:
    if i >= df['columnA'] & <= df['columnB']:
        counts.append(i)

try this :

import pandas as pd
df = pd.DataFrame({'columnA': [1,6,11,16], 'columnB': [5,10,15,20]})
lst = [1,2,3,6,7,12,19]
df['Counts']=0
for index,row in df.iterrows():
    column_a=df.loc[index,'columnA']
    column_b=df.loc[index,'columnB']
    counts=[]
    for value in lst:
        if (value >= column_a) & (value  <= column_b):
            df.loc[index,'Counts']+=1

Output :

在此处输入图像描述

You can construct a Series from original list and use Series.between to check the value that in between range.

lst = [1,2,3,6,7,12,19]
s = pd.Series(lst)
df['Count'] = df.apply(lambda row: s.between(row['columnA'], row['columnB']).sum(), axis=1)
print(df)

   columnA  columnB  Counts  Count
0        1        5       3      3
1        6       10       1      2
2       11       15       1      1
3       16       20       1      1

Series.between has an argument inclusive to determine whether to set each bound as closed or open. Optional values are “both”, “neither”, “left”, “right” .

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