【问题标题】:Pandas preserve fixed-length char field in structured ndarrayPandas 在结构化 ndarray 中保留固定长度的 char 字段
【发布时间】:2014-05-04 16:32:01
【问题描述】:

我有一个带有 dtype 的 numpy 结构化数组,看起来像这样:

In [20]: rectype = np.dtype([
   ....:         ('id',   '<i4'), # int
   ....:         ('price','<f4'), # float
   ....:         ('flag', 'a1'),  # char
   ....:         ('n',    'u1'),  # unsigned char
   ....:         ('r',    'i2'),  # short
   ....:         ('name', 'a4')   # char[4]
   ....:     ])

我想使用 pandas 进行处理,然后取回修改后的 ndarray 以加载到嵌入式设备的内存中。 As has been mentioned here already,pandas 将 char 类型的 dtype 更改为 object,所以结果数组与输入不兼容:

In [21]: nda = np.fromiter([(1, 14.6, 'a', 0, 1, 'car')], dtype=rectype)
In [22]: a2 = pd.DataFrame.from_records(nda).to_records(index=False)
In [23]: a2.dtype
Out[23]: dtype([('id', '<i4'), ('price', '<f4'), ('flag', 'O'), ('n', 'u1'), ('r', '<i2'), ('name', 'O')])
In [24]: rectype.itemsize, a2.dtype.itemsize
Out[24]: (16, 27)

这当然不是很有用。在我的例子中,字符串 的长度是固定的 ,我需要它来适应数据结构。有没有什么简单、有效的方法来取回一个数据结构/dtype 与我开始时完全相同的数组?

【问题讨论】:

    标签: python numpy pandas


    【解决方案1】:

    致电astype():

    pd.DataFrame.from_records(nda).to_records(index=False).astype(rectype)
    

    【讨论】:

    • 谢谢!当你这样说时,这真的是一个麻木的问题。这是一个令人满意的解决方案。尽管如此,我还是认为熊猫往返应该是一种身份转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 2011-01-17
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多