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(...
使用不同的格式化样式来格式化多个列,以及设置输出表列的(包装的)标题。
[更新]
添加:
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
最佳答案
我不得不承认我的问题和它的标题设置不正确,我必须关闭这个主题:
pt.style.format({'percent_on_rent': '{:.0%}'})
我的代码片段中的代码行返回 pandas Styler链接到其父 pandas DataFrame
对象实例的对象实例。 AFAIU 当运行具有此类代码的 Jupiter Notebook 代码单元时,Jupiter Notebook 会捕获 pandas Styler
对象实例并立即将其格式化以在运行单元下输出,同时
print(pt)
打印 pandas DataFrame
对象实例,以及如何通过 print(...)
Python 方法获取此对象实例字符串(?)表示并发送到标准(? ) 输出和由 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 中使用 pandas Styler
对象的主题。更多信息可以用谷歌搜索。
如果我在这个解释中仍然有误,请纠正我。
谢谢!
[更新]
这是一个示例代码,它演示了如何从 Python 方法返回 pandas 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)
关于python - Pandas DataFrame .style.format 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63619863/