python - 比较 2 列值并突出显示差异是否超过 10%?

标签 python pandas styling

我有一个数据框,我想在其中比较2个值,例如A比较A2,B比较B2,C比较C2, 我想计算百分比 abs(A2 - A)/A2 * 100 的差异。现在我想在Excel中将其写为红色如果 差异超过10%

  Cols/Rows    A    A2    B    B2    C    C2
0         A   50    50   150    150  200   200
1         B  200    200  250    300  300   300
2         C  350    500  400    400  450   450

我的方法是迭代每一行并计算%

for index, row in difference_df.iterrows():
    print(abs(row['A2'] - row['A'])/row['A2'] * 100) # for all columns

此外,如果 % 大于 10,如何应用颜色 我也看了造型

def highlight_cells():
    # provide your criteria for highlighting the cells here
    return ['background-color: yellow']

df.style.apply(highlight_cells)

但是如何应用这种样式并将其写入 Excel 呢?

最佳答案

我认为仅需要原始 DataFrame 列和索引的 DataFrame 样式,并按条件设置行 loc :

def highlight_cells(x):
    c1 = 'background-color: yellow'
    c2 = '' 
    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    #define columns names 
    cols = ['A','B','C']
    for c in cols:
        m = ((x[c + '2'] - x[c])/x[c + '2'] * 100 ) > 10
        df1.loc[m, [c, c + '2']] = c1
    return df1

df.style.apply(highlight_cells, axis=None).to_excel('styled.xlsx', engine='openpyxl')

关于python - 比较 2 列值并突出显示差异是否超过 10%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132233/

相关文章:

pandas - 如何对多类数据进行交叉验证?

python - 从 pandas 的文件中读取多个数据帧( block )

python - 如何将带有索引的选定列转换为 Pandas 中的元组列表

pandas - 有没有办法获得 dask 中每组最大的项目?

python - 如何将多个标志传递给 Pandas 中的字符串提取方法?

css - 响应屏幕尺寸时 Logo 重叠文本

html - 我无法摆脱导航链接后面的黑色背景

c++ - 代码信息

python - pytest 测试类调用类方法,类型错误正好需要 2 个参数(给定 1 个)

html - 样式化图像容器