Is there a way to check if NumPy arrays share the same data?

前端 未结 4 1229
夕颜
夕颜 2020-11-30 03:56

My impression is that in NumPy, two arrays can share the same memory. Take the following example:

import numpy as np
a=np.arange(27)
b=a.reshape((3,3,3))
a[0         


        
4条回答
  •  日久生厌
    2020-11-30 04:26

    You can use the base attribute to check if an array shares the memory with another array:

    >>> import numpy as np
    >>> a = np.arange(27)
    >>> b = a.reshape((3,3,3))
    >>> b.base is a
    True
    >>> a.base is b
    False
    

    Not sure if that solves your problem. The base attribute will be None if the array owns its own memory. Note that an array's base will be another array, even if it is a subset:

    >>> c = a[2:]
    >>> c.base is a
    True
    

提交回复
热议问题