我有一個稱為條件的字典rules,我將其應用于資料框df。使用 numpy's 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
有沒有辦法做到這一點?
PS我需要保持字典中條件的優先級。我不想要將優先級映射到字典鍵的單獨字典。
uj5u.com熱心網友回復:
如果您想堅持當前的方法,您可以使用元組來包含每個鍵所需的所有值。在這種情況下,您只需為 提取索引 0 處的值alert并將結果值映射到索引 1priority
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439820.html
下一篇:numpy“TypeError:輸入型別不支持ufunc'bitwise_and'”并且輸入無法安全地強制轉換為任何支持的型別
