Let's say that I have a function that requires NumPy ndarraywith two axes, for example, a data matrix of rows and columns. If a "column" is cut from such an array, this function should also work, so for convenience it should do some internal ones X[:, np.newaxis]. However, I do not want to create a new array object for this, as in some cases this can be expensive.
I am wondering if there is a good way to do this. For example, will the following code be safe (I mean, will global arrays be immutable, like Python lists)?
X1 = np.array([[1,2,3], [4,5,6], [7,8,9]])
X2 = np.array([1,4,7])
def some_func(X):
if len(X.shape) == 1:
X = X[:, np.newaxis]
return X[:,0].sum()
some_func(X2)
some_func(X1[:, 0])
some_func(X1)
I ask because I heard that NumPy arrays are sometimes copied in some cases, however I cannot find a good resource about this. Any ideas?