How can a class that inherits from a NumPy array change its own values?

2024/11/18 12:37:17

I have a simple class that inherits from the NumPy n-dimensional array. I want to have two methods of the class that can change the array values of an instance of the class. One of the methods should set the array of the class instance to the values of a list data attribute of the class instance and the other of the methods should append some list values to the array of the class instance. I'm not sure how to accomplish this, but my attempt is as follows:

import numpyclass Variable(numpy.ndarray):def __new__(cls, name = "zappo"):self = numpy.asarray([]).view(cls)self._values            = [1, 2, 3] # list of valuesreturn(self)def updateNumPyArrayWithValues(self):self = numpy.asarray(self._values)def appendToNumPyArray(self):self = numpy.append(self, [4, 5, 6])a = Variable()
print(a)
a.updateNumPyArrayWithValues()
print(a)

As a quick, preemptive question, would this class survive standard NumPy array operations such as the following?:

>>> v1 = np.array([23, 20, 13, 24, 25, 28, 26, 17, 18, 29])
>>> v1 = v1[v1 >= 20]

So, could I do similar things with my class and have all of its data attributes retained?

Answer

You can do it like this:

class Variable(np.ndarray):def __new__(cls, a):obj = np.asarray(a).view(cls)return objdef updateNumPyArrayWithValues(self):self[1] = 1return self>>> v = Variable([1,2,3])
>>> v
Variable([1, 2, 3])
>>> v.updateNumPyArrayWithValues()
Variable([1, 1, 3])
>>> v[v>1]
Variable([3])
https://en.xdnf.cn/q/71062.html

Related Q&A

Python/SQL Alchemy Migrate - ValueError: too many values to unpack when migrating changes in db

I have several models in SQLAlchemy written and I just started getting an exception when running my migrate scripts: ValueError: too many values to unpackHere are my models:from app import dbROLE_USER …

How to store Dataframe data to Firebase Storage?

Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase?Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Stora…

Multiple characters in Python ord function

Programming beginner here. (Python 2.7)Is there a work around for using more than a single character for Pythons ord function?For example, I have a hex string \xff\x1a which Id like the decimal value …

Get minimum x and y from 2D numpy array of points

Given a numpy 2D array of points, aka 3D array with size of the 3rd dimension equals to 2, how do I get the minimum x and y coordinate over all points? Examples:First:I edited my original example, sin…

Extract Text with its Font Details (Style,Size,color,Italic etc) from a PDF in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic…

How to keep track of status with multiprocessing and pool.map?

Im setting up a multiprocessing module for the first time, and basically, I am planning to do something along the lines offrom multiprocessing import pool pool = Pool(processes=102) results = pool.map(…

How to get time 17:00:00 today or yesterday?

If 17:00:00 today is already passed, then it should be todays date, otherwise - yesterdays. Todays time I get with:test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)But I d…

PyMongo Aggregate how to get executionStats

I am trying to get executionStats of a Particular mongo aggregate query. I run db.command but that doesnt give "execution status"This is what I am trying to do. how to get Python Mongo Aggreg…

Is it possible to do parallel reads on one h5py file using multiprocessing?

I am trying to speed up the process of reading chunks (load them into RAM memory) out of a h5py dataset file. Right now I try to do this via the multiprocessing library. pool = mp.Pool(NUM_PROCESSES) g…

Where is a django validator functions return value stored?

In my django app, this is my validator.py from django.core.exceptions import ValidationError from django.core.validators import URLValidatordef validate_url(value):url_validator = URLValidator()url_inv…