在满足字典条件的任何地方分配字典键和优先级值

Assign dictionary key and priority value wherever conditions from a dictionary are met

我有一个名为 rules 的条件字典,我将其应用于数据框 df。使用 numpy 的 select(),我在 df 中使用第一个条件为 True 的字典键创建了一个新列。代码如下:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': [1, 2, 1, 3], 'col2': [4, 4, 4, 3]})
rules = {"Alert 1": df["col1"] == 1,
         "Alert 2": df["col2"] == 4}
df['alert'] = np.select(rules.values(), rules.keys(), default = None)

df
Out[2]: 
   col1  col2    alert
0     1     4  Alert 1
1     2     4  Alert 2
2     1     4  Alert 1
3     3     3     None

我想更改字典 rules,使其由包含原始条件和优先级值的向量组成。除了要写入 df 的字典键之外,我还希望将此优先级也写入。对rules的修改,以及我尝试将字典键和优先级都写入df:

df = pd.DataFrame({'col1': [1, 2, 1, 3], 'col2': [4, 4, 4, 3]})
rules = {"Alert 1": [df["col1"] == 1, "High"],
         "Alert 2": [df["col2"] == 4, "Medium"]}
df['alert'] = np.select(rules.values()[0], rules.keys(), default = None)
df['priority'] = np.select(rules.values()[0], rules.values()[1], default = None)

我收到一个错误。

理想情况下,我想要输出

   col1  col2    alert  priority
0     1     4  Alert 1      High
1     2     4  Alert 2    Medium
2     1     4  Alert 1      High
3     3     3     None      None

有办法做到这一点吗?

P.S。我需要保持字典中条件的优先级。我不想要一个将优先级映射到字典键的单独字典。

如果您想坚持当前的方法,您可以使用元组来包含每个键所需的所有值。在这种情况下,您只需要为 alert 提取索引 0 处的值,并将结果值映射到 priority

的索引 1
import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': [1, 2, 1, 3], 'col2': [4, 4, 4, 3]})
rules = {"Alert 1": ([df["col1"] == 1, "High"]),
         "Alert 2": ([df["col2"] == 4, "Medium"])}

    
df['alert']  = np.select([x[0] for x in rules.values()], rules.keys(), default = None)
df['priority'] = df['alert'].map({k:v[1] for k,v in rules.items()})

输出

   col1  col2    alert priority
0     1     4  Alert 1     High
1     2     4  Alert 2   Medium
2     1     4  Alert 1     High
3     3     3     None      NaN