【问题标题】:Multiple if conditions on pandas dataframe with different thresholds具有不同阈值的 pandas 数据帧上的多个 if 条件
【发布时间】:2022-01-15 16:44:54
【问题描述】:

我有一个带有多个参数的数据框:

par1      par2      par3      par4      par5       
1.122208  1.054132  1.133250  1.114845  1.183850
1.076445  1.128663  0.998518  1.081816  1.006934
1.077058  1.561871  1.045255  1.120456  1.768667
0.904869  1.183985  0.938095  0.927841  1.201934
0.876596  1.044014  0.877457  0.871429  0.990452
...

需要根据特定阈值检查每个参数的值。我需要检查上述参数中的至少两个是否高于上述阈值。哪些参数高于阈值并不重要,只要其中至少有两个即可。注意par1有一个threshold1,par2有一个threshold2等等,threshold1不同于threshold2,...,threshold5等等。

到目前为止,我已经编写了一个丑陋的嵌套 if 条件,但我想知道这里最好的方法是什么。

【问题讨论】:

  • 上述datafame中的每一个值都是一个参数?那是没有列名的数据框吗?我们在哪里可以找到阈值?您是否为每个值或每列设置了阈值?如果参数高于阈值会发生什么,如果低于阈值会发生什么?你的理想结果是什么?
  • 是的对不起,每一列都是一个参数,所以par1,...,par5。然后,如果其中两个参数高于阈值,我选择相应的行。对于阈值的实际值,我们只说 threshold1 = 1.5,threshold2 = 3,threshold3 = 1.2,threhsold4 =1.5,threshold5=3。
  • 对不起,我不是故意粗鲁的。我只是认为您的问题需要更多信息。
  • 没问题!您需要更多信息吗?因为我要问的是如何在至少满足两个条件时选择一行。如果我只有两列,我会执行 ```df = df[(df.par1 > threshold1) & (df.par2 > threshold2)]。但是,我现在面临的问题是,无论顺序如何,都必须从五列中至少选择两列,这样我就有十种可能的组合。我不知道现在是否清楚。

标签: python pandas


【解决方案1】:

这是否有助于解决您的问题?

df = pd.DataFrame(
  {
    'par1': [1.122208, 1.076445, 1.077058, 0.904869, 0.876596],
    'par2': [1.054132, 1.128663, 1.561871, 1.183985, 1.044014],
    'par3': [1.133250, 0.998518, 1.045255, 0.938095, 0.877457],
    'par4': [1.114845, 1.081816, 1.120456, 0.927841, 0.871429],
    'par5': [1.183850, 1.006934, 1.768667, 1.201934, 0.990452],
  }
)

thresholds = {
  'par1': 0.5,
  'par2': 3,
  'par3': 1.2,
  'par4': 1.1,
  'par5': 3,
}

def check_thresholds(input_row):
  no_over_threshold = sum(
    [value > thresholds[col_name] for col_name, value in input_row.items()]
  )

  if no_over_threshold >= 2:
    return True
  else:
    return False

df['above_thresholds'] = df.apply(check_thresholds, axis=1)

示例输出:

【讨论】:

    【解决方案2】:

    使用 Kelvin Ducray 的示例数据,我们可以将解决方案更进一步,避免 for-loop/apply,并使用 Pandas 的矢量化操作,应该更快:

    thresholds = pd.Series(thresholds)
    
    # compare df with thresholds
    # sum accross the booleans
    # check True or False for >=2
    above_thresholds = df.gt(thresholds).sum(1).ge(2)
    
    df.assign(above_thresholds = above_thresholds)
    
           par1      par2      par3      par4      par5  above_thresholds
    0  1.122208  1.054132  1.133250  1.114845  1.183850              True
    1  1.076445  1.128663  0.998518  1.081816  1.006934             False
    2  1.077058  1.561871  1.045255  1.120456  1.768667              True
    3  0.904869  1.183985  0.938095  0.927841  1.201934             False
    4  0.876596  1.044014  0.877457  0.871429  0.990452             False
    

    【讨论】:

    • 这是一个非常好的答案
    • 难以置信的解决方案!
    猜你喜欢
    • 2020-09-13
    • 2018-05-05
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2021-11-29
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多