我有一个要导出到EXCEL的数据帧.我还想在出口前做一下造型

我有这个代码,它可以更改背景 colored颜色 和文本 colored颜色 ,运行良好,但我想添加以下内容:

df.style.set_properties(**{'background-color': 'black',
                           'color': 'lawngreen',
                           'border-color': 'white'}).to_excel(writer, sheet_name='Sheet1', startrow=rowPos, float_format = "%0.5f")

我需要有字符串和日期的列有白色的文本 colored颜色 ,然后正数是绿色的,负数是红色的.我在造型上直接从documentation只Pandas 身上拿到了这些样式,因为我以前从来没有用过它,不确定如何达到这些效果.

假设我的数据帧如下所示:

StartDate   ExpiryDate  Commodity   Quantity  Price   Total
---------   ----------  ----------  -------   -----   -----
02/28/2024  12/28/2024  HO          10000     -3.89   -38900
02/28/2024  12/28/2024  WPI         10000      4.20    42000

我怎样才能实现我想要的东西?

推荐答案

我会把它分成三个步骤(see the comments #):

st = (
    df.style
    # 1-applying the default styles
    .set_properties(**default_css)
    # 2-formatting the numeric columns
    .apply(
        lambda df_: df_.select_dtypes("number")
        .lt(0).replace({True: tc(neg), False: tc(pos)}),
        axis=None,
    )
    .format(precision=2) # this one is optional
    # 3-formatting the string-like dates and strings
    .map(lambda v: tc(obj) if isinstance(v, str) else "")
)

# st.to_excel("output.xlsx", index=False) # uncomment to make an Excel

发帖主题:Re:Kolibrios

enter image description here

使用的css:

default_css = {
    "background-color": "black",
    "border": "1px solid white",
}

tc = "color: {}".format # css text color
obj, pos, neg = "white", "lawngreen", "red"

Python相关问答推荐

Python 3.12中的通用[T]类方法隐式类型检索

acme错误-Veritas错误:模块收件箱没有属性linear_util'

点到面的Y距离

Polars LazyFrame在收集后未返回指定的模式顺序

韦尔福德方差与Numpy方差不同

需要计算60,000个坐标之间的距离

计算组中唯一值的数量

Django RawSQL注释字段

不能使用Gekko方程'

OpenCV轮廓.很难找到给定图像的所需轮廓

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

如何从比较函数生成ngroup?

如何在验证文本列表时使正则表达式无序?

没有内置pip模块的Python3.11--S在做什么?

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

根据过滤后的牛郎星图表中的数据计算新系列

查找数据帧的给定列中是否存在特定值

某些值的数值幂和**之间的差异

我如何为测试函数的参数化提供fixture 生成的数据?如果我可以的话,还有其他 Select 吗?

当lambda函数作为参数传递时,pyo3执行