tick 数据不会以一张完整的表到达。它们一批一批地来,每次几千条,处理它们的流水线不能等到收盘。Arrow 的答案是记录批:一小块完整的行,一旦生成就能计算、发送或保存,然后被下一批取代。
用通俗的话说这个想法
我们在哪里。 主题 1 说明了什么是列。这个主题把列组合成批和表,它们是所有 Arrow 工具之间传递的对象。下一个主题在它们上做计算,后面的 IPC 和 Flight 主题则讲这些批的发送。
定义记录批
一组等长数组加一个模式:一块连续的行。它是 Arrow 进行计算、流式传输和写入文件的单位。表是块的列表,通常每个批对应一个块。
把表切成批再拼回来
行情表并不是一整块。它由五只股票拼成,因此有五个块,而 to_batches 从不生成横跨两个块的批。所以要求每批最多 10,000 行,得到的是五个约 6,700 行的批,而不是四个 10,000 行的批。table_from_batches 反向操作,把同一块内存包装成表,每批对应一个块,不复制任何值。
# Cut the bars into batches of at most 10,000 rows, then wrap the batches in a table againsizes = batch_sizes(table, 10000)print(len(sizes), "batches:", sizes)batches = table.to_batches(max_chunksize=10000)again = table_from_batches(batches)print("rows:", again.num_rows, "| chunks per column:", again["close"].num_chunks, "| equal:", again.equals(table))
5 batches: [6699, 6698, 6698, 6699, 6699] rows: 33493 | chunks per column: 5 | equal: True
一次处理一个批
batches_total 跨批对一列求和而不把它们拼起来:每批算一个部分和,并带着累计值往下走。内存里一次只需要一个批,所以只要批来自数据流,同样的代码处理一天的数据和十年的数据都行。全是空值的批什么也不加,这就是 pc.sum 对它返回 None、而代码把它当作 0 的原因。
# Add up the volume batch by batch and compare with summing the whole table at onceimport pyarrow.compute as pcprint("by batches :", batches_total(batches, "volume"))print("whole table:", pc.sum(table["volume"]).as_py())
by batches : 3398140608402 whole table: 3398140608402
让表符合某个模式
两个系统要么就模式达成一致,要么无法交流。conform 按消费者期望的顺序和类型取出所需的列,丢弃其余的。cast 是安全转换:它会抛出错误而不是悄悄溢出,所以价格可以变成 float32,而三十亿股的成交量不能变成 int32。
# A consumer wants volume, close and symbol, in that order, with narrower types for close and symboltarget = pa.schema([("volume", pa.int64()), ("close", pa.float32()), ("symbol", pa.large_string())])fitted = conform(table, target)print(fitted.schema)try: conform(table, pa.schema([("volume", pa.int32())]))except Exception as error: print(type(error).__name__ + ": volume does not fit in int32")
volume: int64 close: float symbol: large_string ArrowInvalid: volume does not fit in int32
批的大小需要权衡
批太小,每批都要为头部和函数调用付固定开销;批太大,则放不进缓存或到得太晚。常见范围是几千到几十万行。应根据流水线最慢的环节来选,并实际测量,而不是照抄一个数字。
任务要求
- 1`batch_sizes` 与 `table_from_batches`
table.to_batches(max_chunksize=...)并取各批的num_rows;pa.Table.from_batches(batches)。 - 2`batches_total`对每个批累加
pc.sum(batch[column]).as_py() or 0;不用from_batches,也不用to_pylist。 - 3`conform`
table.select(schema.names).cast(schema)。
快速检查
对一张有五个约 6,700 行块的表调用
table.to_batches(max_chunksize=10000),得到多少个批?请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 切成批:
batch_sizes25 分 - 重新拼起来:
table_from_batches25 分 - 不建大表也能求和:
batches_total25 分 - 匹配目标模式:
conform25 分