python - 将 pandas.DataFrame 转换为字节

标签 python numpy pandas type-conversion dataframe

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

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')

df 看起来像这样:

    a            b                  c
0   10  18446744073709551615    1.324000e+10
1   15  230498234019            3.141590e+00
2   20  32094812309             2.341341e+02

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()

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

OverflowError: Python int too large to convert to C long

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

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

2) 有没有一种方法可以使用每一列的类型信息直接从 DataFrame 转到表示数据的字节字符串。

最佳答案

您可以使用 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

关于python - 将 pandas.DataFrame 转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666860/

相关文章:

python - 为什么二维数组与一维数组的 numpy 点积会产生一维数组?

python - 只有整数、切片 (`:` )、省略号 (`...` )、numpy.newaxis (`None` ) 和整数数组是有效索引

python - Pandas 计算数据框行中的日期差异

python - 如何避免 DataFrame 中两列之间的循环以使用 Google Charts 呈现 Sankey 图?

python - 查找列表的所有可能子列表

python - calendar.month_name 的迭代不能被 strptime() 解析

Python 替换嵌套 for 循环

python - 从列表中选择数据,同时保持顺序

python - Sphinx - 生成对 Trac 票证和变更集的自动引用

python - Python 中的整数数组