numpy: how to fill multiple fields in a structured array at once

2024/10/3 21:29:00

Very simple question: I have a structured array with multiple columns and I'd like to fill only some of them (but more than one) with another preexisting array.

This is what I'm trying:

strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)])
x = np.array([2, 3])
strc[['x', 'y']][0] = x

This gives me this future warning:

main:1: FutureWarning: Numpy has detected that you (may be) writing to an array returned by numpy.diagonal or by selecting multiple fields in a recordarray. This code will likely break in a future numpy release --see numpy.diagonal or arrays.indexing reference docs for details.The quick fix is to make an explicit copy (e.g., doarr.diagonal().copy() or arr[['f0','f1']].copy()).

But even though this is a warning, the structured array doesn't get filled. So far I'm iterating over both arrays and it works but I guess that's highly inefficient. Is there a better way?

Answer

If all the field have the same dtype, you can create a view:

import numpy as np
strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)])
strc_view = strc.view(int).reshape(len(strc), -1)
x = np.array([2, 3])
strc_view[0, [0, 1]] = x

If you want a common solution that can create columns views of any structured array, you can try:

import numpy as np
strc = np.zeros(3, dtype=[('x', int), ('y', float), ('z', int), ('t', "i8")])def fields_view(arr, fields):dtype2 = np.dtype({name:arr.dtype.fields[name] for name in fields})return np.ndarray(arr.shape, dtype2, arr, 0, arr.strides)v1 = fields_view(strc, ["x", "z"])
v1[0] = 10, 100v2 = fields_view(strc, ["y", "z"])
v2[1:] = [(3.14, 7)]v3 = fields_view(strc, ["x", "t"])v3[1:] = [(1000, 2**16)]print strc

here is the output:

[(10, 0.0, 100, 0L) (1000, 3.14, 7, 65536L) (1000, 3.14, 7, 65536L)]
https://en.xdnf.cn/q/70682.html

Related Q&A

Combine date column and time column into datetime column

I have a Pandas dataframe like this; (obtained by parsing an excel file)| | COMPANY NAME | MEETING DATE | MEETING TIME| --------------------------------------------------------…

Matplotlib Plot Lines Above Each Bar

I would like to plot a horizontal line above each bar in this chart. The y-axis location of each bar depends on the variable target. I want to use axhline, if possible, or Line2D because I need to be …

Flask-SQLAlchemy Lower Case Index - skipping functional, not supported by SQLAlchemy reflection

First off. Apologies if this has been answered but I can not find the answer any where.I need to define a lowercase index on a Flask-SQLAlchemy object.The problem I have is I need a models username and…

pip listing global packages in active virtualenv

After upgrading pip from 1.4.x to 1.5 pip freeze outputs a list of my globally installed (system) packages instead of the ones installed inside of my virtualenv. Ive tried downgrading to 1.4 again but …

Scrapy Crawler in python cannot follow links?

I wrote a crawler in python using the scrapy tool of python. The following is the python code:from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLin…

Remove commas in a string, surrounded by a comma and double quotes / Python

Ive found some similar themes on stackoverflow, but Im newbie to Python and Reg Exps.I have a string,"Completely renovated in 2009, the 2-star Superior Hotel Ibis BerlinMesse, with its 168 air-con…

I need help making a discord py temp mute command in discord py

I got my discord bot to have a mute command but you have to unmute the user yourself at a later time, I want to have another command called "tempmute" that mutes a member for a certain number…

How to clip polar plot in pylab/pyplot

I have a polar plot where theta varies from 0 to pi/2, so the whole plot lies in the first quater, like this:%pylab inline X=linspace(0,pi/2) polar(X,cos(6*X)**2)(source: schurov.com) Is it possible b…

Cython and c++ class constructors

Can someone suggest a way to manipulate c++ objects with Cython, when the c++ instance of one class is expected to feed the constructor of another wrapped class as described below? Please look at th…

How to share state when using concurrent futures

I am aware using the traditional multiprocessing library I can declare a value and share the state between processes. https://docs.python.org/3/library/multiprocessing.html?highlight=multiprocessing#s…