You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NumPy或轻量方案打印带行列索引的二维数组?

仅用NumPy或轻量代码实现带索引边框的数组输出

NumPy没有专门内置的功能直接输出带行、列索引边框的二维数组,但可以通过NumPy数组操作配合字符串格式化,或者纯Python轻量代码实现,无需额外依赖Pandas。

方案一:基于NumPy的格式化输出

通过构造表头行和带行索引的内容行,统一格式化打印:

import numpy as np

a = np.arange(6).reshape(2, 3).astype(float)

# 打印列索引表头
col_indices = np.arange(a.shape[1])
header = "     " + "    ".join(f"{idx}" for idx in col_indices)
print(header)

# 逐行打印带行索引的数组内容
for row_idx, row in enumerate(a):
    row_content = "  ".join(f"{val:.1f}" for val in row)
    print(f"{row_idx}  {row_content}")

输出效果:

0    1    2
0  0.0  1.0  2.0
1  3.0  4.0  5.0

方案二:纯Python轻量实现

无需复杂NumPy操作,直接遍历数组完成格式化:

import numpy as np

a = np.arange(6).reshape(2, 3).astype(float)

# 打印列索引
print("     " + "    ".join(str(i) for i in range(a.shape[1])))
# 逐行打印带行索引的内容
for row_idx in range(a.shape[0]):
    row_str = "  ".join(f"{x:.1f}" for x in a[row_idx])
    print(f"{row_idx}  {row_str}")

进阶:对齐更规整的格式

如果需要更严格的对齐效果,可以用固定宽度的字符串格式化:

import numpy as np

a = np.arange(6).reshape(2, 3).astype(float)
col_width = 5  # 每个元素/索引的显示宽度

# 构造列索引表头
header = " " * col_width + "".join(f"{idx:>{col_width}}" for idx in range(a.shape[1]))
print(header)

# 构造每行内容(含行索引)
for row_idx, row in enumerate(a):
    row_content = "".join(f"{val:>{col_width}.1f}" for val in row)
    print(f"{row_idx:>{col_width-1}} {row_content}")

输出效果:

0    1    2
    0  0.0  1.0  2.0
    1  3.0  4.0  5.0

内容的提问来源于stack exchange,提问作者simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:53:21