2

How can I achieve:

>>> foo = np.array([1,2,3])
array([1,2,3])
>>> foo.append(4)
array([1,2,3,4])

Instead of numpy's:

np.append(foo, 4)

I've tried stuff along the lines of:

import numpy as np
class myarrayclass(np.array):
    def append(self, value):
        self.object = np.append(self.object, value)

Also, is it possible to overwrite the numpy class instead of creating my own? I don't need this to work, just wondering if it is possible, thanks in advance!

2
  • Look at the code of np.append before you try this. It is not a list append clone, and shouldn't be treated as one. Commented Nov 13, 2020 at 16:08
  • The closest thing to list append is the resize method. That can add zeros in-place. It may be instructive to look at the code for the np.resize function, which does not operate in place. Rather it uses concatenate and reshape, making a new array. Commented Nov 13, 2020 at 16:39

2 Answers 2

1

The code in dubbbdan's answer definitely has its value but I would suggest the implementation below:

import numpy as np

class MyArrayClass(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return np.ndarray.__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        super()

    def append(self, item):
        return np.append(self, item)

The devil is in the details and that answer is not actually extending the numpy.ndarray class but creating a class wrapper for the append function.

Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure if this is the best way, but here is one approach.

import numpy as np

class myarrayclass(object):
    def __init__(self, in_array):
        self.array = in_array
        
    def append(self, val):
        self.array = np.append(self.array, val)
      
    def show(self):
        return self.array
        
        
foo = np.array([1,2,3])


myarray = myarrayclass(foo)
myarray.append(5)

myarray.show()
#Out[7]: array([1, 2, 3, 5])

When you make an object, you need to initialize it with def __init__(self, in_array). Here I have included a simple append and show method. I included the show method to demonstrate that the append worked.

1 Comment

Thanks for the suggestion! Sadly this isn't really extending the numpy class, and causes you to lose all its functionality. I want to add a function to the already existing functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.