Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

NumPy 数组复制与视图


复制与视图的区别

数组的复制与视图之间的主要区别在于,复制是一个新的数组,而视图只是原始数组的视图。

复制拥有数据,对复制进行的任何更改都不会影响原始数组,对原始数组进行的任何更改都不会影响复制。

视图不拥有数据,对视图进行的任何更改都会影响原始数组,对原始数组进行的任何更改都会影响视图。


复制

示例

创建复制,更改原始数组,并显示两个数组

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42

print(arr)
print(x)
尝试一下 »

复制不应受到对原始数组更改的影响。


视图

示例

创建视图,更改原始数组,并显示两个数组

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42

print(arr)
print(x)
尝试一下 »

视图应该受到对原始数组更改的影响。

在视图中进行更改

示例

创建视图,更改视图,并显示两个数组

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31

print(arr)
print(x)
尝试一下 »

原始数组应该受到对视图更改的影响。



检查数组是否拥有其数据

如上所述,复制拥有数据,而视图不拥有数据,但我们如何检查这一点呢?

每个 NumPy 数组都有一个名为base的属性,如果数组拥有数据,则该属性返回None

否则,base属性将引用原始对象。

示例

打印 base 属性的值以检查数组是否拥有其数据

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

x = arr.copy()
y = arr.view()

print(x.base)
print(y.base)
尝试一下 »

复制返回None
视图返回原始数组。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.