Numpy Storage

The following code snippet demonstrates the way to determine whether a Numpy array points to an actual storage in memory, or holding a view of another array.

1
2
3
4
5
6
7
8
9
10
11
12
13
x = numpy.random.rand(3, 5)
print(x.flags.owndata) # True,真实数组
y = x.reshape((5,3))
print(y.flags.owndata) # False, y is a view of x
print(y.base is x) # True,y holds a reference to x

def find_base_nbytes(a):
"""
get actual number of bytes for array a
"""
if a.base is not None:
return find_base_nbytes(a.base)
return a.nbytes