【问题标题】:I can't seem to update the style in a dataframe in Python我似乎无法在 Python 中更新数据框中的样式
【发布时间】:2021-05-25 04:24:15
【问题描述】:

enter code here首先,我不懂 Python,但我正在将它用于团队项目。我遵循了格子快速入门教程。我能够使用返回的enter code heredata 创建一个数据框,使用它创建一个 html 并从中生成一个 pdf。我花了几个小时!现在我想对数据应用一些基本格式,比如如果金额为负,则将金额设为红色,右对齐金额字段。我已经编写了代码,但我没有使用 Jupyter Lab,我使用的是 atom。我看到了需要 style.render() 才能获得更改的参考,但不知道如何去做。

这是我的代码,它显示 pdf 中的颜色没有变化

# Execute query selecting Transactions table in Plaid database
cur.execute("SELECT description, date, amount FROM transactions")

# Fetch rows
rows = cur.fetchall()

# Close cursor
cur.close()

# Close connection
con.close

# set negative amounts to red
def color_negative_red(amount):
    color = 'red' if amount < 0 else 'black'
    return 'color: %s' % color

# dataframe
df = pd.DataFrame (rows, columns = ["Transaction Description", "Date", "Amount"])
df.style.applymap(color_negative_red)

# convert data frame to <table> and display
html = df.to_html()

text_file = open("test.html", "w")
text_file.write(html)
text_file.close()

# output to a pdf
import pdfkit
pdfkit.from_file('test.html', 'out.pdf')

# open report and pdf in a browser
import webbrowser as wb
wb.open_new_tab('file://C:/Users/Carole/dev/Plaid/quickstart/python/out.pdf')

测试沙箱环境生成的pdf:

最后的变化: # 将负数设置为红色 def color_negative_red(s): 颜色 = '红色' 如果 s

pd.set_option('display.max_rows', 500)

# print DataFrame
print (df)

text_file = open("test.html", "w")
text_file.write(html)
text_file.close()

# output to a pdf
import pdfkit
pdfkit.from_file('test.html', 'out.pdf')

这是我最后一次更改,以使代码能够将金额字符串转换为小数

    from re import sub
    from decimal import Decimal

    new = s.replace("$","").replace(",","")
    value = Decimal(new)

    color = 'red' if value < 0 else 'black'
    return 'color: %s' % color

【问题讨论】:

    标签: python dataframe python-applymap


    【解决方案1】:

    你评估了风格,但没有对它做任何事情。您可以使用样式器的.render() 方法来获取 HTML 输出。

    html = df.style.applymap(color_negative_red).render()
    

    请注意,这不是一个完整的 HTML 页面。它包含一个 HTML 表格和样式信息,但没有 html、head 或 body 标记。

    【讨论】:

    • 非常感谢!这有帮助。显然我的金额字段被视为一个字符串,所以它不喜欢条件表达式。当我将其更改为 color = 'red' if s == '$500.00' else 'black' 我得到了一些红色值!!!
    • 在弄清楚如何从字符串中去掉 $ 和逗号并将其转换为小数之后,我的命令奏效了,一切就绪! def color_negative_red(s):
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2021-05-16
    • 2020-04-07
    • 2016-01-16
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多