gpt4 book ai didi

python - 将数据列添加到只有一行的 numpy rec 数组中

转载 作者:行者123 更新时间:2023-11-30 22:36:49 26 4
gpt4 key购买 nike

我需要将一列数据添加到 numpy rec 数组中。我在这里看到了很多答案,但它们似乎不适用于仅包含一行的记录数组...

假设我有一个记录数组x:

>>> x = np.rec.array([1, 2, 3])
>>> print(x)
rec.array((1, 2, 3),
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8')])

我想将值 4 附加到具有自己的字段名称和数据类型的新列,例如

 rec.array((1, 2, 3, 4), 
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8')])

如果我尝试使用正常的 append_fields 方法添加列;

>>> np.lib.recfunctions.append_fields(x, 'f3', 4, dtypes='<i8', 
usemask=False, asrecarray=True)

然后我最终得到

TypeError: len() of unsized object

事实证明,对于只有一行的记录数组,len(x) 不起作用,而 x.size 可以。如果我改用np.hstack(),我会得到TypeError: invalid type Promotion,如果我尝试np.c_,我会得到一个不想要的结果

>>> np.c_[x, 4]
array([[(1, 2, 3), (4, 4, 4)]],
dtype=(numpy.record, [('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8')]))

最佳答案

创建初始数组,使其形状为 (1,);注意额外的括号:

In [17]: x = np.rec.array([[1, 2, 3]])

(如果x是您无法以这种方式控制的输入,则可以在中使用它之前使用x = np.atleast_1d(x) append_fields().)

然后确保 append_fields 中给出的值也是长度为 1 的序列:

In [18]: np.lib.recfunctions.append_fields(x, 'f3', [4], dtypes='<i8', 
...: usemask=False, asrecarray=True)
Out[18]:
rec.array([(1, 2, 3, 4)],
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8')])

关于python - 将数据列添加到只有一行的 numpy rec 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com