Pandas 数据帧转储到 excel 颜色格式

Pandas dataframe dump to excel with color formatting

我有一个很大的 pandas 数据框 df 作为:

Sou ATC   P25   P75 Avg
A   11    9     15  10
B   6.63  15    15  25
C   6.63  5     10  8

我想将此数据帧打印到 excel 文件,但我想将格式应用于 excel 文件的每一行,以便将以下规则应用于 ATC 中的单元格和Avg 列:

excel中的示例显示如下:

我不知道该如何处理。

您可以使用 style.Styler.apply with DataFrame of styles with numpy.select for filling by masks created by DataFrame.ltDataFrame.gt:

def color(x): 
   c1 = 'background-color: red'
   c2 = 'background-color: green'
   c3 = 'background-color: yellow'
   c = ''

   cols = ['ATC','Avg']
   m1 = x[cols].lt(x['P25'], axis=0)
   m2 = x[cols].gt(x['P75'], axis=0)
   arr = np.select([m1, m2], [c1, c2], default=c3)

   df1 = pd.DataFrame(arr, index=x.index, columns=cols)
   return df1.reindex(columns=x.columns, fill_value=c)

df.style.apply(color,axis=None).to_excel('format_file.xlsx', index=False, engine='openpyxl')