【问题标题】:Convert bytea to ndarray of nd.float32将 bytea 转换为 nd.float32 的 ndarray
【发布时间】:2023-02-17 01:24:23
【问题描述】:

我有一个 np.float32 的 ndarray,它以 bytea 格式保存在 Postgres 数据库中:

import pandas as pd
import numpy as np
import sqlite3

myndarray=np.array([-3.55219245e-02, 1.33227497e-01, -4.96977456e-02, 2.16857344e-01], dtype=np.float32)
myarray=[myndarray.tobytes()]
mydataframe=pd.DataFrame(myarray, columns=['Column1'])
mydataframe.to_sql('mytable', sqlite3.connect("/tmp/floats.sqlite"))

在 SQLITE3 中,这将产生:

CREATE TABLE IF NOT EXISTS "mytable" ("index" INTEGER, "Column1" TEXT);
INSERT INTO mytable VALUES(0,X'707f11bdca6c083edd8f4bbdda0f5e3e');

在 Postgresql 中,这将产生:

mydatabase=# select * from mytable;
 index |              Column1
-------+------------------------------------
     0 | \x707f11bdca6c083edd8f4bbdda0f5e3e

哪种格式是bytea。如何将 \x707f... 转换回 myndarray?这里没有专家,我发现了很多关于 frombuffer()、python2 buffer()memoryview() 的晦涩文档,但我离正确的结果还很远。

到目前为止我最好的是:

np.frombuffer(bytearray('707f11bdca6c083edd8f4bbdda0f5e3e', 'utf-8'), dtype=np.float32)

这是完全错误的(myndarray 有 4 个值):

[2.1627062e+23 1.6690035e+22 3.3643249e+21 5.2896255e+22 2.1769183e+23
 1.6704162e+22 2.0823326e+23 5.2948159e+22]

【问题讨论】:

    标签: python pandas postgresql numpy bytea


    【解决方案1】:
    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 2021-08-09
    • 2012-08-24
    • 1970-01-01
    • 2017-12-14
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多