给定数据为
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
最佳答案
我测试检查显示为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
关于python - 设置 pandas 打印输出的列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944834/