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

如何在KDB中以二进制格式保存矩阵并通过NumPy读取?

Solution for Saving KDB Matrix to Binary & Reading with NumPy

1. Fixing the 'type' Error When Saving Matrix in KDB

You’re spot-on—KDB’s save command only works with tables, which is why you hit that 'type' error trying to save a matrix (a list of lists, a general list type). Here are two simple workarounds:

Option 1: Use set to Save the Matrix Directly

Skip save entirely and use set—this command can serialize any KDB data type (including matrices) to a binary file without converting to a table:

matrix: (til 10)*/:til 10;
// Save the matrix to a binary file
set `:matrix.bin matrix;

// To load it back later in KDB:
loaded_matrix: get `:matrix.bin;

Option 2: Convert Matrix to Table for save (If You Prefer Table Format)

If you specifically need to use save, convert your matrix into a table first, then convert it back when loading:

matrix: (til 10)*/:til 10;
// Convert matrix to a table (column names can be custom; here we use `c0`c1...`c9)
matrix_table: flip `c0`c1`c2`c3`c4`c5`c6`c7`c8`c9!matrix;
// Save the table
save `:matrix.tab;

// Load back and convert to matrix:
loaded_table: load `:matrix.tab;
loaded_matrix: value flip loaded_table;

2. Reading KDB Binary Files with NumPy (Without KDB-Python Library)

Unfortunately, you can’t directly use np.fromfile to read KDB’s native binary files (saved with set or save). KDB uses its own proprietary serialization format—these files include type metadata and structural info, not just raw numeric bytes.

To make the matrix readable by NumPy, write it as raw binary data (no KDB-specific formatting) from KDB first:

matrix: (til 10)*/:til 10;
// Convert matrix to your desired numeric type (KDB's `float` maps to NumPy's float64)
float_matrix: `float$matrix;
// Flatten the matrix to a 1D list
flat_matrix: raze float_matrix;
// Write raw binary bytes to file (0: is KDB's raw file write command)
0:`:matrix.raw 0: flat_matrix;

Now you can read this raw file with NumPy by specifying the correct dtype and reshaping:

import numpy as np
// Read raw bytes and reshape back to 10x10 matrix
numpy_matrix = np.fromfile('C:/q/w32/matrix.raw', dtype='float64').reshape(10, 10)
  • If you saved integers (KDB’s long type), use dtype='int64' instead.
  • Double-check that the reshape dimensions match what you saved (10x10 here).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:03:16