NumPy ndarray.base

The numpy.ndarray.base attribute returns the base object from which the array memory is derived. If an array is a view of another array, base points to the original array; otherwise, it is None.

Syntax

</>
Copy
ndarray.base

Return Value

Returns the base object from which memory is shared if the array is a view. If the array owns its data, it returns None.


Examples

1. Checking the Base Object of an Independent Array

When an array owns its data, the base attribute returns None.

</>
Copy
import numpy as np

# Creating an independent array
arr = np.array([1, 2, 3, 4, 5])

# Checking the base attribute
print(arr.base)

Output:

None

Since arr is an independent array and owns its memory, base returns None.

2. Checking the Base Object of a View

If an array is created as a view of another array, base points to the original array.

</>
Copy
import numpy as np

# Creating an original array
arr = np.array([10, 20, 30, 40, 50])

# Creating a view of the original array
view_arr = arr.view()

# Checking the base attribute of the view
print(view_arr.base)

Output:

[10 20 30 40 50]

Since view_arr is a view of arr, its base attribute points to arr.

3. Checking the Base Object of a Sliced Array

A sliced array shares memory with the original array, making it a view with a non-None base.

</>
Copy
import numpy as np

# Creating an original array
arr = np.array([5, 10, 15, 20, 25])

# Creating a sliced array (view)
sliced_arr = arr[1:4]

# Checking the base attribute of the sliced array
print(sliced_arr.base)

Output:

[ 5 10 15 20 25]

Since sliced_arr is a view of arr, its base attribute points to arr, showing that it shares memory with the original array.

4. Checking the Base Object of a Copy

Unlike views, a copy of an array owns its memory, so its base is None.

</>
Copy
import numpy as np

# Creating an original array
arr = np.array([100, 200, 300, 400])

# Creating a copy of the array
copy_arr = arr.copy()

# Checking the base attribute of the copied array
print(copy_arr.base)

Output:

None

Since copy_arr is a separate copy of arr and does not share memory, its base returns None.