我花了几个小时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}}

推荐答案

您的代码中存在一些问题:

  • "背景"中的拼写错误
  • 如果未应用样式,则函数应返回''None,而不是"background-color:"
  • 你应该输出df.style.applymap的回报,而不是df

要设置小数,请在to_excel中使用float_format="%0.1f":

# And then I tried apply background-color and none of them worked..
def highlight_cell(val):
    color = 'yellow' 
    return f"background-color: {color}" if val == 'Movies' else ''

(df.style.applymap(highlight_cell)
   .to_excel('retails.xlsx', engine='openpyxl', float_format="%0.1f")
)

输出:

excel highlight

不使用EXCEL导出的格式:

(df.style.applymap(highlight_cell)
   .format({'Margin': '{:.1f}', 'Margin_Rate': '{:.2f}'})
   #.to_excel('retails.xlsx', engine='openpyxl')
)

输出:

pandas formatting

Python相关问答推荐

如何计算列表列行之间的公共元素

TARete错误:类型对象任务没有属性模型'

不理解Value错误:在Python中使用迭代对象设置时必须具有相等的len键和值

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

如果值不存在,列表理解返回列表

Telethon加入私有频道

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

如何让这个星型模式在Python中只使用一个for循环?

我如何根据前一个连续数字改变一串数字?

移动条情节旁边的半小提琴情节在海运

未知依赖项pin—1阻止conda安装""

如何使用正则表达式修改toml文件中指定字段中的参数值

如何在Python中将超链接添加到PDF中每个页面的顶部?

如何将泛型类类型与函数返回类型结合使用?

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

按条件添加小计列

python的文件. truncate()意外地没有截断'

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

无法在盐流道中获得柱子