numpy:如何向现有结构化数组添加一列? [英] numpy: How to add a column to an existing structured array?

查看:103
本文介绍了numpy:如何向现有结构化数组添加一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个起始数组,例如:

I have a starting array such as:

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

第一列是 int,第二列是 floatslist.我需要添加一个名为 'USNG'str 列.

The first column is an int and the second is a list of floats. I need to add a str 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 array as a new column, so I can output some information to that column for each row.

当我执行以下操作时:

numpy.append(array, x, axis=1)

我收到以下错误:

'TypeError: invalid type promotion'

我也试过 vstackhstack

推荐答案

您必须创建一个包含新字段的新 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') 添加到该列表的末尾来创建一个新的数据类型:

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

现在创建一个结构化数组,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:如何向现有结构化数组添加一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆