格式£sign with pandas to \u htm

2024-06-25 05:44:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用to_html格式化DataFrame的输出,以便以英镑作为前缀显示值。你知道吗

df['gross'].map('£{0:,.0f}'.format)

退货:

Attempt with symbol

df['gross'].map('£{0:,.0f}'.format)

退货:

Attempt with hex

我哪里出错了?你知道吗


Tags: toformatmapdataframedfhtmlwithsymbol
2条回答

如果您只想将£symbol添加到HTML输出中,那么不要更改数据帧本身—您将把所有数字字段转换为字符串,并失去将它们视为数字的能力。to_html允许您指定如何使用参数formatters格式化内容。你知道吗

举个例子:

import pandas as pd
data = dict( index = ['A','B','C','D'], values = [1,2,3,4])
df = pd.DataFrame(data)

format_pounds = dict( values = '£{}'.format) # add £ to column 'values'
html = df.to_html(formatters = format_pounds)

我不知道你哪里出错了,但你可以尝试使用样式器:

df = pd.DataFrame(data=[[1,2], [3.2, 4.01]], columns=['gross', 'fish'])
s = df.style
s.format({'gross': "£{0:,.0f}".format})
s.render()

产生:

相关问题 更多 >