我試圖使用 2 個不同的列來設定 Pandas Dataframe 的樣式。只要條件與列本身有關,我就成功了,但是當它依賴于另一個時,我無法獲得所需的結果。
如果“Date I”是過去的,我想為“Date II”中的單元格著色。
def date_pii(row):
ret = ["" for _ in row.index]
print(row['Date PI'])
if row['Date PI'] < datetime.now():
ret[row.index.get_loc("Date PII")] = "background-color: red"
return ret
styler = df3.style \
.applymap(lambda x: 'background-color: %s' % 'red' if x <= datetime.now() else '', subset=['Date PI']) \
.applymap(lambda x: 'background-color: %s' % 'yellow' if x < datetime.now() timedelta(days=30) else '',
subset=['Date PII']) \
.applymap(lambda x: 'background-color: %s' % 'orange' if x <= datetime.now() else '', subset=['Date PII']) \
.applymap(lambda x: 'background-color: %s' % 'grey' if pd.isnull(x) else '', subset=['Date PI'])\
.applymap(lambda x: 'background-color: %s' % 'grey' if pd.isnull(x) else '', subset=['Date PII'])\
.apply(date_pii, axis=1) ----> THIS IS THE ISSUE
styler.to_excel(writer, sheet_name='Report Paris', index=False)
在運行時,我收到以下錯誤:
ValueError: Function <function generate_report_all.<locals>.date_pii at 0x7fd3964d9160> returned the wrong shape.
Result has shape: (532,)
Expected shape: (532, 10)
資料框如下所示:

“Date PII”中的第一個橙色單元格是正確的,但是,其余的(PI 為紅色)我希望它們也變成紅色。
謝謝您的幫助!
uj5u.com熱心網友回復:
解決此類問題的一般方法是將指定的列作為 a 傳遞subset給
設定 DataFrame 總是相對于當前日期隨機生成(樣式將保持一致,而日期則不會):
import numpy as np
import pandas as pd
from numpy.random import Generator, MT19937
norm_today = pd.Timestamp.now().normalize()
rng = Generator(MT19937(1023))
def md(lower_bound, upper_bound, rng_=rng):
return pd.Timedelta(days=rng_.integers(lower_bound, upper_bound))
df3 = pd.DataFrame({
'Desc': [
'PII within 30 days', # PII yellow
'PII in past and PI in future', # PII orange
'PI past', # Both red
'PI empty', # grey
'PII empty', # grey
'PII in future but not within 30 days' # No Styles
],
'Date PII': [norm_today md(1, 10), norm_today - md(1, 10),
norm_today, norm_today, np.nan,
norm_today md(40, 50)],
'Date PI': [norm_today, norm_today md(1, 10),
norm_today - md(1, 10), np.nan, norm_today,
norm_today]
})
| 描述 | 日期 PII | 日期 PI |
|---|---|---|
| 30 天內的 PII | 2021-11-06 00:00:00 | 2021-11-03 00:00:00 |
| 過去的 PII 和未來的 PI | 2021-10-31 00:00:00 | 2021-11-11 00:00:00 |
| PI過去 | 2021-11-03 00:00:00 | 2021-11-01 00:00:00 |
| PI 空 | 2021-11-03 00:00:00 | 鈉鹽 |
| PII 空 | 鈉鹽 | 2021-11-03 00:00:00 |
| PII 在未來但不是在 30 天內 | 2021-12-19 00:00:00 | 2021-11-03 00:00:00 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/347965.html
下一篇:向量化最大距離函式
