python - 是否可以在 IPython 控制台中显示熊猫样式?
问题描述
是否可以在 iPython 控制台中显示熊猫样式?Jupyter 笔记本中的以下代码
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 5)})
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
axis=1)
df.style.format({'B': "{:.2%}"})
正确产生
在控制台中我只得到
In [294]: df.style.format({'B': "{:.2%}"})
Out[294]: <pandas.io.formats.style.Styler at 0x22f3f4fe780>
是否有可能在这里实现类似的结果,或者样式引擎是否依赖于 html 前端?
提前感谢您的帮助。
解决方案
我相信样式器确实需要一个 html 前端,比如 jupyter,即使它只格式化数字(而不是字体或颜色)。
请参阅此处使用 Pandas Styler。
为了将列转换为特定格式,应该使用以下.map
方法:
df = pd.DataFrame({'A': np.linspace(1, 5, 5)})
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
axis=1)
df['C']=df['B'].map("{:.2%}".format)
print(df, end='\n\n')
print(df.dtypes)
A B C
0 1.0 1.329212 132.92%
1 2.0 -0.770033 -77.00%
2 3.0 -0.316280 -31.63%
3 4.0 -0.990810 -99.08%
4 5.0 -1.070816 -107.08%
A float64
B float64
C object
dtype: object
缺点是 df['C'] 不再是一个数字,因此您无法再对数据框进行正确排序。
推荐阅读
- ios - .element::-webkit-scrollbar{display:none} 在 Safari 和 iOS 设备中不起作用
- atom-editor - 如何验证 atom 包是否在 atom 编辑器中正确启动
- javascript - Jest 不会模拟(设置间谍)所需的功能
- php - PHP 文件未执行所有 3 个查询
- mysql - MYSQL:为给定过滤器选择一行和键的最大值
- javascript - 用逗号分割逗号分隔的字符串
- java - JAVA - HTTP 请求 - 得到错误的响应
- python-3.x - 双循环
- fonts - 无法在高级 pdf 模板中使用 Calibri 字体
- java - 使用正则表达式在 UNSPSC 中获取商品级别