我正在嘗試在 excel 上自動執行一些任務,其中一些包括設定沒有任何紅色值的單元格(我的 DataFrame 維度中的空單元格而不是它之外),在檢查了以前的類似答案后,我嘗試了以下操作:
import pandas as pd
# Create a dataframe
df = pd.read_excel(r'input.xls', sheet_name='sheet1')
print(df)
df.style.applymap(lambda x: 'background-color : yellow' if x>1 else '')
# create excel writer object
writer = pd.ExcelWriter(r'Output.xls')
# write dataframe to excel
df.to_excel(writer)
# save the excel
writer.save()
print('DataFrame is written successfully to Excel File.')
我也嘗試過其他方式,比如
def color(row):
if row.isnull().values.any() == True:
return ['background-color: red'] * len(row)
return [''] * len(row)
# Apply the function
df.style.apply(color, axis=1)
這些似乎都不起作用,在控制臺中,我列印了正確的值,并且得到了一個輸出檔案,其中包含從 0 開始的附加行列舉,但輸出 excel 檔案中沒有任何顏色
我在 excel 中的資料集有 x x y 維度,每個單元格可以包含數字(十進制)或文本,具體取決于列名
uj5u.com熱心網友回復:
pandas Styler物件與df創建它的物件是一個單獨的物件。要將樣式化的 DataFrame 寫出到 excel 我們需要使用實際的 Styler 物件 not df。最簡單的方法是使用Styler.to_excel:
# Save Styler Object for Later
styler = df.style
# Apply Styles (This can be chained or on separate lines)
styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
styler.apply(color, axis=1)
# Export the styler to excel
styler.to_excel('Output.xls', index=False)
方法鏈也有效:
df.style \
.applymap(lambda x: 'background-color : yellow' if x > 1 else '') \
.apply(color, axis=1) \
.to_excel('Output.xls', index=False)
*注意:index=False確保輸出中不包含 DataFrame 索引。(“從 0 開始的附加行列舉”)
我們還可以以類似的方式將pd.ExcelWriter與Styler一起使用:
# Save Styler Object for Later
styler = df.style
# Apply Styles (This can be chained or on separate lines)
styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
styler.apply(color, axis=1)
with pd.ExcelWriter('Output.xls') as writer:
styler.to_excel(writer, index=False)
作為一項總體改進,我們可以通過傳遞axis=None給Styler.apply并在一個函式中執行所有修改來在DataFrame 級別設定樣式:
def color(df_):
styles_df = pd.DataFrame('', index=df_.index, columns=df_.columns)
# Color cells yellow where they are greater than 1
styles_df[df_ > 1] = 'background-color: yellow'
# Color rows red where there are any null values across rows
styles_df.loc[df.isnull().any(axis=1), :] = 'background-color: red'
return styles_df
with pd.ExcelWriter('Output.xls') as writer:
df.style.apply(color, axis=None).to_excel(writer, index=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/383043.html
