我有一个数据框,我想在其中比较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/