我花了几个小时try 所有可能的Pandas 样式方法来设置Excel表格的条件格式,但都没有奏效…… 我有一个下面这样的数据框.
Category Month Sales Margin Margin_Rate
0 TV July 50000 10354.64 0.207093
1 Steros August 45000 39379.38 0.875097
2 Phones September 22000 8130.23 0.369556
3 Cell Phones October 90000 8089.23 0.089880
4 Video Consoles November 12000 8564.69 0.713724
5 Video Games December 7000 3187.74 0.455391
6 Wearables January 28000 8470.51 0.302518
7 Tablets February 75000 8649.36 0.115325
8 Movies March 25000 20372.73 0.814909
9 Laptops April 100000 62309.34 0.623093
(1).我试着用Pandas 的style.Format()进行数字格式化,但从来没有成功过. (2).try 根据条件应用单元格背景 colored颜色 时,使用的是style.Apply或yle le.applymap,但也从未成功过.
以下是我的代码:
# First of all I tried style.format(precision=1)
df.style.format(precision=1) <--- This causes TypeError: format() got an unexpected keyword argument 'precision'. Any idea why?
# And then I tried the dictionary approach. No error from this but it does not format numbers
df.style.format({'Margin': '{:.1f}', 'Margin_Rate': '{:.2f}'})
# And then I tried apply background-color and none of them worked..
def highlight_cell(val):
color = 'yellow' if val == 'Movies' else ''
return f"bacground-color: {color}"
df.style.applymap(highlight_cell)
# No number formatting nor background color change in the excel sheet...
df.to_excel('retails.xlsx', engine='openpyxl')
它们都不起作用. 有什么 idea 吗? 还是我错过了什么?
谢谢.
[ Adding df.to_dict() as Kraigolas recommends ]:个
{'Category': {0: 'TV', 1: 'Steros', 2: 'Phones', 3: 'Cell Phones', 4: 'Video Consoles', 5: 'Video Games', 6: 'Wearables', 7: 'Tablets', 8: 'Movies', 9: 'Laptops'}, 'Month': {0: 'July', 1: 'August', 2: 'September', 3: 'October', 4: 'November', 5: 'December', 6: 'January', 7: 'February', 8: 'March', 9: 'April'}, 'Sales': {0: 50000, 1: 45000, 2: 22000, 3: 90000, 4: 12000, 5: 7000, 6: 28000, 7: 75000, 8: 25000, 9: 100000}, 'Margin': {0: 10354.64, 1: 39379.38, 2: 8130.23, 3: 8089.23, 4: 8564.69, 5: 3187.74, 6: 8470.51, 7: 8649.36, 8: 20372.73, 9: 62309.34}, 'Margin_Rate': {0: 0.2070928, 1: 0.8750973333333333, 2: 0.3695559090909091, 3: 0.08988033333333333, 4: 0.7137241666666667, 5: 0.45539142857142856, 6: 0.3025182142857143, 7: 0.1153248, 8: 0.8149092, 9: 0.6230934}}