*編輯了 DataFrame 隨機生成器
我有 2 個 dfs,一個用作另一個的掩碼。
rndm = pd.DataFrame(np.random.randint(0,15,size=(100, 4)), columns=list('ABCD'))
rndm_mask = pd.DataFrame(np.random.randint(0,2,size=(100, 4)), columns=list('ABCD'))
我想使用 2 個條件來更改 rndm 中的值:
- 值是列的模式嗎?
- rndm_mask == 1
到目前為止有效的方法:
def colorBoolean(val):
return f'background-color: {"red" if val else ""}'
rndm.style.apply(lambda _: rndm_mask.applymap(colorBoolean), axis=None)
# helper function to find Mode
def highlightMode(s):
# Get mode of columns
mode_ = s.mode().values
# Apply style if the current value is in mode_ array (len==1)
return ['background-color: yellow' if v in mode_ else '' for v in s]
問題:
我不確定如何以rndm中的值僅在它們匹配兩個條件時突出顯示的方式鏈接這兩個函式(即 value 必須是 column 中最常見的值,并且在rndm_mask中為True)。
我很感激任何建議!謝謝
uj5u.com熱心網友回復:
試試這個,因為你的 df_bool 資料框是一個掩碼(相同的索引),那么你可以在樣式函式中參考 df_bool 物件,其中 x.name 是通過 df.apply 傳入的列的名稱:
df = pd.DataFrame({'A':[5.5, 3, 0, 3, 1],
'B':[2, 1, 0.2, 4, 5],
'C':[3, 1, 3.5, 6, 0]})
df_bool = pd.DataFrame({'A':[0, 1, 0, 0, 1],
'B':[0, 0, 1, 0, 0],
'C':[1, 1, 1, 0, 0]})
# I want to use 2 conditions to change the values in df:
# Is the value the mode of the column?
# df_bool == 1
# What works so far:
def colorBoolean(x):
return [f'background-color: red' if v else '' for v in df_bool[x.name]]
# helper function to find Mode
def highlightMode(s):
# Get mode of columns
mode_ = s.mode().values
# Apply style if the current value is in mode_ array (len==1)
return ['background-color: yellow' if v in mode_ else '' for v in s]
df.style.apply(colorBoolean).apply(highlightMode)
輸出:

或者其他方式:
df.style.apply(highlightMode).apply(colorBoolean)
輸出:

更新
Highlight where both are true:
def highlightMode(s):
# Get mode of columns
mode_ = s.mode().values
# Apply style if the current value is in mode_ array (len==1)
return ['background-color: yellow' if (v in mode_) & b else '' for v, b in zip(s, df_bool[s.name])]
df.style.apply(highlightMode)
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474764.html
