python - 为熊猫打印设置列宽
问题描述
给定数据为
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
推荐阅读
- css - 媒体查询未在不同的测试屏幕上申请相同的设备分辨率
- javascript - 我想展示 2 个不同的抽签动画,svg1 和 svg2
- c# - 当一种样式更改为另一种样式时,有什么方法可以触发 Word VSTO 中的事件?
- visual-studio-code - VSC 平台特定设置
- amazon-web-services - 在参数描述 CloudFormation 中使用 URL
- webpack - require.context 调用期间“适当的加载程序”出错
- css - 在 Sass 中使用 Bootstrap 容器宽度计算
- authentication - Google auth.authenticate_user() 导致请求格式错误
- c# - 未找到类中的 C# 问题 dll 入口点
- api - 限制用户从 IP 地址访问的最佳 HTTP 状态代码是什么