首页 > 解决方案 > 为熊猫打印设置列宽

问题描述

给定数据为

In [403]: data=pd.DataFrame(
     ...: {
     ...: 'A':['hello there', 1],
     ...: 'B':['something', 44],
     ...: })

In [404]: data
Out[404]:
             A          B
0  hello there  something
1            1         44

我希望能够按照以下方式做一些事情

pd.set_output_width(4)

这将导致前一个数据帧的终端输出沿着

In [404]: data
Out[404]:
    A      B
0  hell  some
1   1     44

标签: pythonpandas

解决方案


我测试检查显示到4,但它会被省略号截断长度4+

with pd.option_context('display.max_colwidth', 3):
    print (data)
             A          B
0  hello there  something
1   1           44       

with pd.option_context('display.max_colwidth', 4):
    print (data)
     A    B
0  ...  ...
1    1   44

with pd.option_context('display.max_colwidth', 5):
    print (data)
      A     B
0  h...  s...
1     1    44

with pd.option_context('display.max_colwidth', 6):
    print (data)
       A      B
0  he...  so...
1      1     44

with pd.option_context('display.max_colwidth', 8):
    print (data)
         A        B
0  hell...  some...
1        1       44

我认为很接近,您需要的是切片 -apply对于所有列切片:

print (data.astype(str).apply(lambda x: x.str[:4]))
      A     B
0  hell  some
1     1    44

applymap用于元素切片:

print (data.astype(str).applymap(lambda x: x[:4]))
      A     B
0  hell  some
1     1    44

推荐阅读