Numpy,将列添加到现有结构化数组

编程入门 行业动态 更新时间:2024-10-28 14:36:13
本文介绍了Numpy,将列添加到现有结构化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的起始数组:

I have a starting array as such:

[(1, [-112.01268501699997, 40.64249414272372]) (2, [-111.86145708699996, 40.4945008710162])]

其中第一列是int,第二列是其中有浮点数的元组.我需要添加一个名为USNG的字符串列.

where the first column is an int and the second is a tuple with floats in there. I need to add a string column called USNG.

然后我像这样创建一个结构化的numpy数组:

I then create a structured numpy array as such:

dtype = numpy.dtype([('USNG', '|S100')]) x = numpy.empty(array.shape, dtype=dtype)

我想将x numpy数组附加到现有数组上,以添加新列,以便为每一行向该列输出一些信息.当我执行以下操作时:

I want to append the x numpy array to the existing one to add a new column so I can output some information to that column for each row. When I do the following:

numpy.append(array, x, axis=1)# I've also tried vstack and hstack

我收到以下错误:

'TypeError: invalid type promotion'

有关为什么发生这种情况的任何建议?

Any suggestions on why this is happening?

谢谢

推荐答案

您必须创建一个包含新字段的新dtype.

You have to create a new dtype that contains the new field.

例如,这里是a:

In [86]: a Out[86]: array([(1, [-112.01268501699997, 40.64249414272372]), (2, [-111.86145708699996, 40.4945008710162])], dtype=[('i', '<i8'), ('loc', '<f8', (2,))])

a.dtype.descr是[('i', '<i8'), ('loc', '<f8', (2,))];即字段类型列表.我们将通过在列表的末尾添加('USNG', 'S100')来创建新的dtype:

a.dtype.descr is [('i', '<i8'), ('loc', '<f8', (2,))]; i.e. a list of field types. We'll create a new dtype by adding ('USNG', 'S100') to the end of that list:

In [87]: new_dt = np.dtype(a.dtype.descr + [('USNG', 'S100')])

现在创建一个 new 结构化数组b.我在这里使用了zeros,因此字符串字段将从值''开始.您也可以使用empty.然后,这些字符串将包含垃圾,但是如果您立即为其分配值,则无所谓.

Now create a new structured array, b. I used zeros here, so the string fields will start out with the value ''. You could also use empty. The strings will then contain garbage, but that won't matter if you immediately assign values to them.

In [88]: b = np.zeros(a.shape, dtype=new_dt)

将现有数据从a复制到b:

In [89]: b['i'] = a['i'] In [90]: b['loc'] = a['loc']

现在是b:

In [91]: b Out[91]: array([(1, [-112.01268501699997, 40.64249414272372], ''), (2, [-111.86145708699996, 40.4945008710162], '')], dtype=[('i', '<i8'), ('loc', '<f8', (2,)), ('USNG', 'S100')])

在新字段中填写一些数据:

Fill in the new field with some data:

In [93]: b['USNG'] = ['FOO', 'BAR'] In [94]: b Out[94]: array([(1, [-112.01268501699997, 40.64249414272372], 'FOO'), (2, [-111.86145708699996, 40.4945008710162], 'BAR')], dtype=[('i', '<i8'), ('loc', '<f8', (2,)), ('USNG', 'S100')])

更多推荐

Numpy,将列添加到现有结构化数组

本文发布于:2023-10-28 08:56:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536156.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   结构化   Numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!