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

Python中如何按指定格式批量打印多组表格数据?

解决方法:按指定格式打印Numpy数组数据

首先,咱们先修正你代码里的两个关键问题:

  1. 数据数组的语法错误:你定义data时,两个子数组之间缺少逗号,这会直接导致代码报错,正确的写法应该是用逗号分隔每个子数组。
  2. 循环逻辑错误:你原来的循环只是分别遍历表头和整行数据,没有将表头与对应位置的数据元素一一配对,所以输出会重复打印整行内容。

纯Numpy实现方案

import numpy as np

# 修正语法错误后的数组定义
headings = np.array(["userID","name","bookingID"])
data = np.array([[1111111,"Joe Bloggs",2222222], [1212121,"Jane Doe",3333333]])

# 遍历每一行数据
for row in data:
    # 将表头与对应数据元素配对,拼接成"key value"格式的片段
    line_segments = [f"{heading} {value}" for heading, value in zip(headings, row)]
    # 将所有片段合并成一行并打印
    print(' '.join(line_segments))

如果你想用Pandas(对应你代码里提到的df.values)

如果你原本是想用Pandas处理数据,也可以这样实现:

import pandas as pd
import numpy as np

headings = np.array(["userID","name","bookingID"])
data = np.array([[1111111,"Joe Bloggs",2222222], [1212121,"Jane Doe",3333333]])

# 转换为DataFrame
df = pd.DataFrame(data, columns=headings)

# 遍历每一行并按格式打印
for _, row in df.iterrows():
    line_segments = [f"{col} {row[col]}" for col in df.columns]
    print(' '.join(line_segments))

输出结果

两种方法都会得到你想要的格式:

userID 1111111 name Joe Bloggs bookingID 2222222
userID 1212121 name Jane Doe bookingID 3333333

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:48:36