简体   繁体   English

基于索引的style.format

[英]Index based style.format

You can specify a format for each column by using df.style.format() , however, i want this behavior but then index based instead of column based. 您可以使用df.style.format()来为每列指定一种格式,但是,我想要这种行为,但随后基于索引而不是基于列。 I realise its a bit more tricky because a column has a specific datatype, and a row can be mixed. 我意识到它有点棘手,因为列具有特定的数据类型,并且行可以混合。

Is there a workaround to get it anyway? 有解决办法吗? The df.style.apply() method has the flexibility, but i don't think it supports number formatting, only (CSS) styling. df.style.apply()方法具有灵活性,但我认为它不支持数字格式,仅支持(CSS)样式。

Some sample data: 一些样本数据:

import pandas as pd

df = pd.DataFrame([[150.00, 181.00, 186.00],
                   [  5.85,   3.73,   2.12]], 
                  index=['Foo', 'Bar'],
                  columns=list('ABC'))

在此处输入图片说明

If i transpose the Dataframe, is easy: 如果我转置数据框,很简单:

mapper = {'Foo': '{:.0f}',
          'Bar': '{:.1f}%'}   

df.T.style.format(mapper)

在此处输入图片说明

But i want this formatting without transposing, something like: 但是我想要这种格式而不进行转置,例如:

df.style.format(mapper, axis=1)

You may not need to use the Styler class for this if the target is to re-format row values. 如果目标是重新设置行值的格式,则可能不需要为此使用Styler类。 You can use that mapper dictionary to match the formats you want, through a map and apply combination by row. 您可以使用该mapper字典通过map匹配所需的格式,并逐行apply组合。 The following should be a decent start: 以下应该是一个不错的开始:

df.apply(lambda s: s.map(mapper.get(s.name).format), axis=1)

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM