将pandas.DataFrame转换为字节

Pau*_*man 7 python numpy type-conversion dataframe pandas

我需要将存储在a中的数据pandas.DataFrame转换为字节字符串,其中每列可以具有单独的数据类型(整数或浮点).这是一组简单的数据:

df = pd.DataFrame([ 10, 15, 20], dtype='u1', columns=['a'])
df['b'] = np.array([np.iinfo('u8').max, 230498234019, 32094812309], dtype='u8')
df['c'] = np.array([1.324e10, 3.14159, 234.1341], dtype='f8')
Run Code Online (Sandbox Code Playgroud)

和df看起来像这样:

    a            b                  c
0   10  18446744073709551615    1.324000e+10
1   15  230498234019            3.141590e+00
2   20  32094812309             2.341341e+02
Run Code Online (Sandbox Code Playgroud)

DataFrame对各类型列的都知道df.dtypes,所以我想这样做:

data_to_pack = [tuple(record) for _, record in df.iterrows()]
data_array = np.array(data_to_pack, dtype=zip(df.columns, df.dtypes))
data_bytes = data_array.tostring()
Run Code Online (Sandbox Code Playgroud)

这通常工作正常,但在这种情况下(由于存储的最大值df['b'][0].上面的第二行将元组数组转换为np.array具有给定类型的一组导致以下错误:

OverflowError: Python int too large to convert to C long
Run Code Online (Sandbox Code Playgroud)

错误结果(我相信)在第一行中将记录提取为Series具有单个数据类型(默认为float64),并且float64为最大值选择的表示uint64不能直接转换回uint64.

1)既然DataFrame已经知道每列的类型有没有办法绕过创建一行元组输入到类型numpy.array构造函数?或者有没有比上面概述的更好的方法来保留这种转换中的类型信息?

2)有没有办法直接从DataFrame表示数据的字节字符串使用每列的类型信息.

ali*_*i_m 9

您可以使用df.to_records()将数据帧转换为 numpy recarray,然后调用.tostring()将其转换为字节字符串:

rec = df.to_records(index=False)

print(repr(rec))
# rec.array([(10, 18446744073709551615, 13240000000.0), (15, 230498234019, 3.14159),
#  (20, 32094812309, 234.1341)], 
#           dtype=[('a', '|u1'), ('b', '<u8'), ('c', '<f8')])

s = rec.tostring()
rec2 = np.fromstring(s, rec.dtype)

print(np.all(rec2 == rec))
# True
Run Code Online (Sandbox Code Playgroud)