我经常在终端上使用Series和DataFrames。Series的默认__repr__返回一个减少的样本,其中有一些头部和尾部值,但其余的都没有。
是否有一种内置的方式来漂亮地打印整个系列/数据帧?理想情况下,它应该支持适当的对齐,可能是列之间的边界,甚至可能是不同列的颜色编码。
我经常在终端上使用Series和DataFrames。Series的默认__repr__返回一个减少的样本,其中有一些头部和尾部值,但其余的都没有。
是否有一种内置的方式来漂亮地打印整个系列/数据帧?理想情况下,它应该支持适当的对齐,可能是列之间的边界,甚至可能是不同列的颜色编码。
当前回答
当然,如果这个经常出现,就做一个这样的函数。您甚至可以将其配置为在每次启动IPython时加载:https://ipython.org/ipython-doc/1/config/overview.html
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
至于颜色,过于复杂的颜色对我来说听起来适得其反,但我同意像bootstrap的.table条纹之类的东西会很好。您总是可以创建一个问题来建议这个功能。
其他回答
试试这个
pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
当然,如果这个经常出现,就做一个这样的函数。您甚至可以将其配置为在每次启动IPython时加载:https://ipython.org/ipython-doc/1/config/overview.html
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
至于颜色,过于复杂的颜色对我来说听起来适得其反,但我同意像bootstrap的.table条纹之类的东西会很好。您总是可以创建一个问题来建议这个功能。
脚本
没有人提出过这种简单的纯文本解决方案:
from pprint import pprint
pprint(s.to_dict())
产生如下结果:
{'% Diabetes': 0.06365372374283895,
'% Obesity': 0.06365372374283895,
'% Bachelors': 0.0,
'% Poverty': 0.09548058561425843,
'% Driving Deaths': 1.1775938892425206,
'% Excessive Drinking': 0.06365372374283895}
Jupyter記本嗎
此外,当使用Jupyter笔记本时,这是一个很好的解决方案。
注意:pd.Series()没有.to_html(),所以必须转换为pd.DataFrame()
from IPython.display import display, HTML
display(HTML(s.to_frame().to_html()))
产生如下结果:
datasroller的创建部分是为了解决这个问题。
pip install datascroller
它将数据帧加载到终端视图中,你可以用鼠标或方向键“滚动”,有点像终端上的Excel工作簿,支持查询、高亮显示等。
import pandas as pd
from datascroller import scroll
# Call `scroll` with a Pandas DataFrame as the sole argument:
my_df = pd.read_csv('<path to your csv>')
scroll(my_df)
披露:我是datascroller的作者之一
不需要侵入设置。有一个简单的方法:
print(df.to_string())