首页 > 解决方案 > 为什么 pandas 的 style.format 在 spyder 中不起作用?

问题描述

也许我错过了一些东西,我有这个:

import pandas as pd

series1 = pd.Series({'DEPOSITOS': 353254})
series2 = pd.Series({'DEPOSITOS': 54464.43})
series3 = pd.Series({'COLOCACIONES': 6381763761})
series4 = pd.Series({'COLOCACIONES': 687513761})
series5 = pd.Series({'%PROV': 0.95})
series6 = pd.Series({'%PROV': 0.25})

top100v3 = pd.DataFrame([series1, series2, series3,series4, series5, series6])

top100v3.style.format({"DEPOSITOS": "{:,.0f}"})

但是当我运行它时,它不会改变数据框(top100v3),它只是返回:

C:\Users\yvs\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py:253: FutureWarning: elementwise comparison failed; 而是返回标量,但将来将执行元素比较 res_values = method(rvalues) Out[1]:

标签: pythonpandasspyder

解决方案


显然 style.format 使用 html 和 css 支持,而 spyder 不支持这一点,但 jupyer notebook 支持,所以如果我想继续使用 spyder,我必须更改将格式应用于列的方式

#for one column
top100v3["DEPOSITOS"] = top100v3["DEPOSITOS"].apply(lambda x : "{:,.0f}".format(x))

#for many columns  
col_formatlist = ["DEPOSITOS", "COLOCACIONES"]

for col in col_formatlist:
top100v3[col] = top100v3[col].apply(lambda x: f'{x:,.0f}'.format(x))

top100v3["%PROV"] = top100v3["%PROV"].apply(lambda x: "{:.2%}".format(x))

有关更多格式,请查看此https://mkaz.blog/code/python-string-format-cookbook/


推荐阅读