将列添加到结构化的Numpy数组

编程入门 行业动态 更新时间:2024-10-28 12:31:02
本文介绍了将列添加到结构化的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']),并返回地图上投影位置的两个数组x和y(可以).

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).

我可以使用单独的向量x和y,但是我想用两个新列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数组

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

发布评论

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

>www.elefans.com

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