簡體   English   中英

如何檢查值列表是否在兩列中存在的值范圍內?

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

我是 python 新手,還在學習。 我有一些值,我想檢查它們是否在特定范圍內。 范圍被放置在 df 表的兩列中,所以基本上我想逐行檢查表並檢查是否有任何值在范圍內並計算它們

columnA  columnB   Counts
1           
6           10
11          15
16          20

並且數字在列表中

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

最終輸出:

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

我想到的是

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

嘗試這個 :

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

輸出 :

在此處輸入圖像描述

您可以從原始列表構造一個系列並使用Series.between來檢查介於范圍之間的值。

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有一個參數inclusive來確定是否將每個邊界設置為關閉或打開。 可選值為“both”、“neither”、“left”、“right”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM