Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you tell if an array is a view of another?

Tags:

python

numpy

Do numpy arrays keep track of their "view status"?

import numpy
a = numpy.arange(100)
b = a[0:10]
b[0] = 100
print a[0]
# 100 comes out as it is a view
b is a[0:10]
# False (hmm how to ask?)

What I am looking for is numpy.isview() or something.

I want this for code profiling to be sure that I am doing things correctly and getting views when I think I am.

like image 875
Brian Larsen Avatar asked Feb 06 '12 17:02

Brian Larsen


People also ask

How can I tell if a NumPy array is a view?

You can use the base attribute to determine if the NumPy array numpy. ndarray is a view or a copy. In addition, np. shares_memory() can be used to determine if two arrays share memory.

How do I check if a NumPy array is in another array?

By using Python NumPy np. array_equal() function or == (equal operator) you check if two arrays have the same shape and elements. These return True if it has the same shape and elements, False otherwise.

How do you check if elements of an array are in another array Python?

Use numpy. isin() to find the elements of a array belongs to another array or not. it returns a boolean array matching the shape of other array where elements are to be searched.

Does reshape make a copy?

With a compatible order, reshape does not produce a copy.


2 Answers

the array also has a base attribute:

a = np.arange(10)
print a.base
None

b = a[2:9]
print b.base is a
True

c = b[:2]
print c.base is b
True
print c.base is a
False
like image 106
Bi Rico Avatar answered Oct 03 '22 20:10

Bi Rico


ndarray.flags.owndata tells you whether the array owns its data. In your example:

In [18]: a.flags.owndata
Out[18]: True

In [19]: b.flags.owndata
Out[19]: False

It's clearly not as precise as what you're asking, but it's the best that I know of.

like image 21
NPE Avatar answered Oct 03 '22 18:10

NPE