熊猫DataFrame .style.format不起作用

时间:2020-08-27 15:58:04

标签: python pandas formatting styles

import pandas as pd 
import numpy as np  

data = [['benzine', 1], ['benzine', 0], 
        ['diesel', 1], ['diesel', 0], ['diesel', 1],
        ['electro', 1], ['electro', 0], ['electro', 1],['electro', 1]]
df = pd.DataFrame(data, columns = ['engine_type', 'rented']) 

pt = df.pivot_table(index=['engine_type'], values= ['rented'], aggfunc=[np.mean])
pt.set_axis(['percent_on_rent'], axis = 'columns', inplace = True)
pt.style.format({'percent_on_rent': '{:.0%}'})
  
print(pt)

当前输出:

             percent_on_rent
engine_type
benzine             0.500000
diesel              0.666667
electro             0.750000

预期输出:

             percent_on_rent
engine_type
benzine             50%
diesel              67%
electro             75$

注意:以下代码

print(pt.to_string(float_format=lambda x: '{:.0%}'.format(x)))

可以,但是我想使用.style.format(...使用不同的格式样式来格式化几列,以及设置输出表列的(包装的)标题。

[UPDATE]

已添加:

print(pd.versions())

结果:

INSTALLED VERSIONS
------------------
commit           : None
python           : 3.8.3.final.0
python-bits      : 64
OS               : Windows
OS-release       : 10
machine          : AMD64
processor        : AMD64 Family 23 Model 24 Stepping 1, AuthenticAMD
byteorder        : little
LC_ALL           : None
LANG             : None
LOCALE           : English_United States.1252

pandas           : 1.0.5
numpy            : 1.19.1
pytz             : 2020.1
dateutil         : 2.8.1
pip              : 20.2.2
setuptools       : 41.2.0
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 2.11.2
IPython          : 7.17.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : 3.3.0
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : None
pytables         : None
pytest           : None
pyxlsb           : None
s3fs             : None
scipy            : None
sqlalchemy       : None
tables           : None
tabulate         : None
xarray           : None
xlrd             : 1.2.0
xlwt             : None
xlsxwriter       : None
numba            : None
None

1 个答案:

答案 0 :(得分:0)

我必须承认我的问题及其标题设置不正确,并且必须关闭此主题:

pt.style.format({'percent_on_rent': '{:.0%}'})
我的代码段中的

代码行返回链接到其父级熊猫DataFrame对象实例的熊猫Styler对象实例。 AFAIU当运行带有此类代码的Jupiter Notebook代码单元时,Jupiter Notebook捕获熊猫Styler对象实例,并立即对其格式化,以在运行单元中输出

print(pt)

打印熊猫DataFrame对象实例,以及如何通过print(...) Python方法获取此对象实例字符串(?)表示并将其发送到standard(?)输出,并由Jupiter Notebook和仅在Jupiter Notebook源代码中才能找到在运行代码的单元下呈现的图像。 在Jupiter Notebook单元中编写并运行以下代码:

my_styler = pt.style.format({'percent_on_rent': '{:.0%}'})
my_styler

等同于

pt.style.format({'percent_on_rent': '{:.0%}'})

同时

my_styler = pt.style.format({'percent_on_rent': '{:.0%}'})
print(my_styler)

将输出

<pandas.io.formats.style.Styler object at 0x...>

Here is a link涉及在Jupiter Notebook中使用熊猫Styler对象的主题。可以查询更多信息。

如果我在此说明中仍然有误,请纠正我。

谢谢!

[更新]

这里是示例代码,演示了如何从Python方法返回熊猫Styler对象实例,然后使用display(...)方法在Jupiter Notebook中将它们输出:

import numpy as np
import pandas as pd

def rc1():
    return np.random.choice(['benzine', 'diesel', 'electro'])

def rc2():
    return 1 if np.random.choice([True, False]) else 0

def test_pandas_styler(caption):
    # fill list
    data = []
    for i in range(21): data.append([rc1(), rc2()])
       
    # make data frame
    df = pd.DataFrame(data, columns = ['engine_type', 'rented']) 
    
    # make pivot table
    pt = df.pivot_table(index=['engine_type'], values= ['rented'], aggfunc=[np.mean]).reset_index()
    pt.set_axis(['engine type', 'percent on rent'], axis = 'columns', inplace = True)
    
    # style pivot table
    st = pt.style.format({'percent on rent': '{:.0%}'}).hide_index()    
    st.set_table_styles([
           dict(selector="th", props=[('color', 'darkblue'), 
                                      ('vertical-align', 'top')]),
           dict(selector="th:first-child", props=[('max-width', '70px'), ('text-align', 'left')]),
           dict(selector="th:last-child", props=[('max-width', '50px')]),
           dict(selector="td:first-child", props=[('text-align', 'left')])
            ])    
    st.caption = caption
    
    return st

for f in [test_pandas_styler('Test {}'.format(i)) for i in range(1,4)]:
    display(f)

Test output in Jupiter Notebook