Python 比较两列值并突出显示差异是否超过10%?

Python 比较两列值并突出显示差异是否超过10%?,python,pandas,styling,Python,Pandas,Styling,我有一个数据框,我想比较两个值,比如a比较A2,B比较B2,C比较C2, 我想计算一下abs(A2-A)/A2*100的百分比差异。现在我想在excel中用highted作为红色来编写它 差额超过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

我有一个数据框,我想比较两个值,比如a比较A2,B比较B2,C比较C2, 我想计算一下abs(A2-A)/A2*100的百分比差异。现在我想在excel中用highted作为红色来编写它 差额超过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?

我认为只需要通过原始的
数据框
列和索引,并按条件设置行,使用:


使用xlsxwriter完成这样的任务好吗,还是应该使用pandas样式?嗯,我认为如果使用百分比数据创建新列,是否可以格式化此新列,请检查。但如果需要动态条件,如我的答案中所示,需要样式是的,我需要动态条件。我真正的数据帧是多索引的,让我用that@TarunK-如果存在多索引,是否可能更改数据样本,如果我的解决方案存在问题?
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')