html 设置默认数据格式化,如何格式化IPandy html显示的Pandas数据帧?

Julien Marre..

11

很久以前就问过这个问题.那时候,熊猫还没有包括pd.Styler.它已在版本中添加0.17.1.

以下是如何使用它来实现您期望的目标以及更多目标:

中心标题

右对齐任意数字列

左对齐其他列.

为您想要的数字列添加格式化程序

使它成为每列具有相同的宽度.

这是一些示例数据:

In [1]:

df = pd.DataFrame(np.random.rand(10,3)*2000, columns=['A','B','C'])

df['D'] = np.random.randint(0,10000,size=10)

df['TextCol'] = np.random.choice(['a','b','c'], 10)

df.dtypes

Out[1]:

A float64

B float64

C float64

D int64

TextCol object

dtype: object

让我们使用df.style以下格式:

# Construct a mask of which columns are numeric

numeric_col_mask = df.dtypes.apply(lambda d: issubclass(np.dtype(d).type, np.number))

# Dict used to center the table headers

d = dict(selector="th",

props=[('text-align', 'center')])

# Style

df.style.set_properties(subset=df.columns[numeric_col_mask], # right-align the numeric columns and set their width

**{'width':'10em', 'text-align':'right'})\

.set_properties(subset=df.columns[~numeric_col_mask], # left-align the non-numeric columns and set their width

**{'width':'10em', 'text-align':'left'})\

.format(lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x), # format the numeric values

subset=pd.IndexSlice[:,df.columns[numeric_col_mask]])\

.set_table_styles([d]) # center the header

K3BFA.png

请注意.format,您可以很好地设置全局默认值,而不是调用子集列pd.options.display.float_format:

pd.options.display.float_format = lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x)

值得一提的是`df.style.set_prop .... render()`返回所需的html,而`df.to_html`则没有. (4认同)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值