将列添加到结构化的Numpy数组 [英] Adding columns to a structured Numpy array

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

问题描述

我在geo.dat

id  lon  lat inhab  name
 1   9.  45.   100  Ciriè
 2  10.  45.    60  Acquanegra

我在ndarray

import numpy as np
data = np.genfromtxt('geo.dat', dtype=None, names=True)

到目前为止,很好,我有一个数据结构,可以按列名进行寻址

so far, so good, I have a data structure that I can address by column name

print(data['name'][1]) #>>> Acquanegra

下一步,还有一个问题-我有一个函数接受输入的两个向量 地理坐标(当然是data['LON']data['LAT']),并返回地图上投影位置的两个数组xy(可以).

Next step, and question — I have a function that takes in input two vectors of geographical coordinates (data['LON'] and data['LAT'] of course) and returns two arrays x and y of projected positions on a map (this works ok).

我可以使用单独的向量xy,但是我想用两个新列data['x']data['y']来扩充data.我的天真尝试

I can live with separate vectors x and y but I'd like to augment data with two new columns, data['x'] and data['y']. My naive attempt

data['x'], data['y'] = convert(data['LON'], data['LAT'])

举起了ValueError: no field of name x,告诉我data具有字典的某些特征,但字典没有.

raised a ValueError: no field of name x, teaching me that data has some traits of a dictionary but a dictionary is not.

是否可以按照我的意愿做? tia

Is it possible to do as I want? tia

请考虑.hstack()不适用于结构化数组或记录数组,大多数以前的答案仅适用于同构数组(沃伦在下面的评论中提到了例外).

Please consider that .hstack() doesn't work with structured arrays aka record arrays, most previous answers work only for homogeneous arrays (the exception is mentioned in below comment by Warren).

PS我不想使用pandas.

推荐答案

您可以使用np.lib.recfunctions:

import numpy.lib.recfunctions as rfn

data = rfn.append_fields(data, ['x', 'y'], [x, y])

这篇关于将列添加到结构化的Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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