所以我有一个TimeSeries数据帧df,它有‘n’列和大量的行:

df = pd.read_csv('percentiles.csv', index_col=0, parse_dates=True)

最后3行df如下所示:

ATH ATL 12MH 12ML 3MH 3ML 1MH 1ML
Date
2024-02-16 6 0 8 -1 11 -8 15 -16
2024-02-19 8 -1 10 -2 11 -5 22 -11
2024-02-20 8 0 13 0 16 -2 40 -3

我正try 将此df导出为表格(Pdf),单元格的背景 colored颜色 取决于其列中的值的高或低.我发现的一种方法是使用百分比.

我做了另一个三角形,以确定每列的长度:

percentiles = [0, 0.1, 0.2, 0.8, 0.9]
df2 = df.quantile(q=percentiles, axis=0)

df2包含每列的百分位值,看起来像这样:

ATH ATL 12MH 12ML 3MH 3ML 1MH 1ML
0.0 0.0 -115.0 0.0 -74.0 0.0 -122.0 0.0 -136.0
0.1 0.0 -8.0 0.0 -8.0 1.0 -26.1 4.0 -44.1
0.2 1.8 -4.0 1.0 -4.0 3.0 -14.0 7.0 -28.0
0.8 10.0 0.0 11.0 0.0 20.0 -1.0 33.0 -4.0
0.9 15.0 0.0 16.0 0.0 29.0 0.0 44.1 -2.0

我做了一个字典, for each 百分比指定一种 colored颜色 :

percentile_color = {0:'red', 0.1: 'orange', 0.2: 'white', 0.8: 'lightgreen', 0.9: 'green'}

我希望每列中的每个单元格都按其所在列的百分位数的 colored颜色 进行着色.我可以为一系列(列)这样做,但一旦我创建了数据帧,其中每一列都有不同的百分位数,我就卡住了.有什么建议吗?谢谢!

推荐答案

您可以在使用quantilemerge_asof的自定义函数中使用styler.apply:

def get_colors(s):
    s = s.astype(float).sort_values()
    return (pd.merge_asof(s.reset_index(), s.quantile(q=percentiles).reset_index())
              .set_index('Date')['index']
              .map(lambda x: f'background-color: {percentile_color.get(x, "")}')
           )

df.style.apply(get_colors)

输出:

color dataframe per quantile in column

请注意,您可以 Select 单元格的 colored颜色 是前一个分位数还是下一个分位数为direction:

def get_colors(s):
    s = s.astype(float).sort_values()
    return (pd.merge_asof(s.reset_index(), s.quantile(q=percentiles).reset_index(),
                         direction='forward')
              .set_index('Date')['index']
              .map(lambda x: f'background-color: {percentile_color.get(x, "")}')
           )

df.style.apply(get_colors)

输出:

color dataframe per quantile in column

而且,对于重复的分位数,您可以使用以下命令强制获取最小的分位数:

def get_colors(s):
    s = s.astype(float).sort_values()
    return (pd.merge_asof(s.reset_index(),
                          s.quantile(q=percentiles).drop_duplicates().reset_index())
              .set_index('Date')['index']
              .map(lambda x: f'background-color: {percentile_color.get(x, "")}')
           )

df.style.apply(get_colors)

输出:

color dataframe per quantile in column

Python相关问答推荐

DataFrame groupby函数从列返回数组而不是值

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

将jit与numpy linSpace函数一起使用时出错

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

基于索引值的Pandas DataFrame条件填充

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

使用Python更新字典中的值

判断solve_ivp中的事件

python中csv. Dictreader. fieldname的类型是什么?'

OpenCV轮廓.很难找到给定图像的所需轮廓

使用Openpyxl从Excel中的折线图更改图表样式

将CSS链接到HTML文件的问题

没有内置pip模块的Python3.11--S在做什么?

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

设置索引值每隔17行左右更改的索引

如何在基于时间的数据帧中添加计算值

如何在Django查询集中生成带有值列表的带注释的字段?

将鼠标悬停在海运`pairplot`的批注/高亮显示上

基于2级列表的Pandas 切片3级多索引