我有一个这样的起始数组:
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,将列添加到现有结构化数组
发布评论