亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將新值與之前的值進行比較,如果在 Excel 中不相同則進行標記(使用 Python)

將新值與之前的值進行比較,如果在 Excel 中不相同則進行標記(使用 Python)

PHP
瀟瀟雨雨 2023-11-09 16:42:34
我在 Excel 中有一個數據框 df,其中包含我希望與以前的值進行比較的值。如果當前值與之前的值不比較,我希望突出顯示 Excel 中的單元格。這是我的數據:COL1  match9     1  False8     3  False2     2  True3     1  False4     2  False5     2  False期望的結果:df['match'] = df.COL1.eq(df.COL1.shift())print (df)COL1  match9     1  False8     3  False2     2  True3     1  False4     2  False5     2  False并突出顯示 Excel 中的“False”值這就是我正在做的:import xlsxwriterworkbook = xlsxwriter.Workbook('c:\\temp\\df.xlsx')worksheet = workbook.add_worksheet()def highlight_cells():return ['background-color: yellow']df.style.apply(highlight_cells)     df['match'] = df.COL1.eq(df.COL1.shift())我不確定如何將所有這些放在一起,最終突出顯示 Excel 中與以前的值不匹配的任何單元格。我目前正在研究。任何建議都將不勝感激。
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

您可以通過對單元格應用 Excel 條件格式來實現此目的,如下所示:


import pandas as pd



# Create a Pandas dataframe from some data.

df = pd.DataFrame({'Data1': [10, 20, 30, 20, 15, 30, 45],

                   'Data2': [11, 20, 30, 21, 15, 31, 45]})


# Create a Pandas Excel writer using XlsxWriter as the engine.

writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')


# Convert the dataframe to an XlsxWriter Excel object.

df.to_excel(writer, sheet_name='Sheet1')


# Get the xlsxwriter workbook and worksheet objects.

workbook  = writer.book

worksheet = writer.sheets['Sheet1']


# Add a format. Green fill with dark green text.

green_format = workbook.add_format({'bg_color': '#C6EFCE',

                                    'font_color': '#006100'})


# Apply a conditional format to the cell range.

worksheet.conditional_format(1, 2, 7, 2, {'type':     'cell',

                                          'criteria': 'equal to',

                                          'value':    '=$B2',

                                          'format':   green_format})


# Close the Pandas Excel writer and output the Excel file.

writer.save()

輸出:

https://img1.sycdn.imooc.com/654c9ba90001706704590335.jpg

查看完整回答
反對 回復 2023-11-09
  • 1 回答
  • 0 關注
  • 168 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號