【发布时间】:2021-11-13 21:05:54
【问题描述】:
我正在尝试创建一个表格,用买卖价格从 DataFrame 中估算利润:
import pandas as pd
from df2img import df2img
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
'Fruits': ['Apple', 'Apple', 'Apple', 'Orange', 'Banana', 'Orange'],
'BuyPrice': [1000, 3000, 2400, 3000, 800, 1500],
'SellPrice': [1200, 2800, 2500, 2500, 700, 1750]
}
)
# Display DataFrame
print('Original DataFrame:\n')
print(df)
# Add Profit percentage column
df['Profit'] = (df['SellPrice']-df['BuyPrice'])*100/df['BuyPrice']
df['Profit'] = df.apply(lambda x: "{:,.2f} %".format(x['Profit']), axis=1)
# Rename column titles
df = df.rename({'BuyPrice': 'Buy Price', 'SellPrice': 'Sell Price'}, axis=1)
# Highlight positive and negative profits
def highlight_cols(s):
color = 'red' if type(s) != str and s < 0 else 'green'
return 'color: %s' % color
df.style.applymap(highlight_cols, subset=['Profit'])
print('\nFinal DataFrame:\n')
print(df)
# Now create an image file for the table
df2img(
df,
file="table_fruits.png",
header_color="white",
header_bgcolor="orange",
row_bgcolors=["lightgray", "white"],
font_size=10.0,
col_width=1.5,
row_height=0.3
)
plt.show()
在这里,我想将正利润用绿色着色,将负利润用红色着色。 df.style.applymap 仅在我不在同一单元格上的 Jupyter 笔记本上使用 df2img 时才有效(尽管颜色不正确)。因此DataFrameStyler 指令不会传递给最终的图像文件。任何不那么复杂的解决方案?
输出:
【问题讨论】:
-
所以我不知道您使用的是哪个版本的 df2img,但当前版本不支持您正在使用的调用。除此之外,您还可以使用
df['Profit'] = df.apply(lambda x: "{:,.2f} %".format(x['Profit']), axis=1)将整列转换为字符串。出于这个原因,在您的突出显示功能color = 'red' if type(s) != str and s < 0 else 'green'type(s) != str确保所有单元格都是绿色的。 -
@HenryEcker 是的,这是真的。但是我以后如何格式化浮点数?
-
您是否特别需要 plotly 表格样式?这就是您使用 df2img 的原因,还是使用所有 Styler 操作和不同的模块导出到 png 也可以?我在条件样式中询问的唯一原因是 Styler 的用途,它与使用它非常相似,然后尝试重新定义样式以进行 plotly toundertsand。
-
是的,我愿意。如果没有 Styler 也可以做到这一点,那也可以。
标签: python pandas image dataframe pandas-styles