官术网_书友最值得收藏!

Creating array views and copies

In the example about ravel(), views were brought up. Views should not be confused with the construct of database views. Views in the NumPy universe are not read only and you don't have the possibility to protect the underlying information. It is crucial to know when we are handling a shared array view and when we have a replica of the array data. A slice of an array, for example, will produce a view. This entails that if you assign the slice to a variable and then alter the underlying array, the value of this variable will change. We will create an array from the famed Lena picture, and then create a view and alter it at the final stage. The Lena image array comes from a SciPy function.

  1. Create a copy of the Lena array:
    acopy = lena.copy()
  2. Create a view of the array:
    aview = lena.view()
  3. Set all the values in the view to 0 with a flat iterator:
    aview.flat = 0

The final outcome is that only one of the pictures depicts the model. The other ones are censored altogether, as shown in the following screenshot:

Refer to the following code of this tutorial (it is without comments to save space; for the full code, have a look at copy_view.py), which shows the behavior of array views and copies:

import scipy.misc
import matplotlib.pyplot as plt

lena = scipy.misc.lena()
acopy = lena.copy()
aview = lena.view()
plt.subplot(221)
plt.imshow(lena)
plt.subplot(222)
plt.imshow(acopy)
plt.subplot(223)
plt.imshow(aview)
aview.flat = 0
plt.subplot(224)
plt.imshow(aview)
plt.show()

As you can see, by altering the view at the end of the program, we modified the original Lena array. This resulted in three blue (or black if you are reading the print version of this book) pictures. The copied array was unchanged. It is crucial to remember that views are not read only.

主站蜘蛛池模板: 穆棱市| 浮梁县| 稻城县| 崇信县| 金湖县| 萝北县| 内江市| 九寨沟县| 石景山区| 图们市| 阳春市| 鄢陵县| 濮阳县| 舞钢市| 基隆市| 泗水县| 丹阳市| 朔州市| 平远县| 易门县| 鹤峰县| 馆陶县| 明光市| 班戈县| 泾源县| 会泽县| 武功县| 刚察县| 锦屏县| 剑河县| 宝鸡市| 肃北| 波密县| 留坝县| 衡南县| 盐边县| 福贡县| 丰原市| 漠河县| 巩留县| 虎林市|