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

  • Python Data Analysis
  • Ivan Idris
  • 249字
  • 2021-08-05 17:31:52

Fancy indexing

Fancy indexing is indexing that does not involve integers or slices, which is conventional indexing. In this tutorial, we will practice fancy indexing to set the diagonal values of the Lena photo to 0. This will draw black lines along the diagonals, crossing through them.

The following is the code for this tutorial with comments taken away. The full code is in fancy.py of this book's code bundle:

import scipy.misc
import matplotlib.pyplot as plt

lena = scipy.misc.lena()
xmax = lena.shape[0]
ymax = lena.shape[1]
lena[range(xmax), range(ymax)] = 0
lena[range(xmax-1,-1,-1), range(ymax)] = 0
plt.imshow(lena)
plt.show()

The following is a brief explanation of the preceding code:

  1. Set the values of the first diagonal to 0.

    To set the diagonal values to 0, we need to specify two different ranges for the x and y values (coordinates in a Cartesian coordinate system):

    lena[range(xmax), range(ymax)] = 0
  2. Set the values of the other diagonal to 0.

    To set the values of the other diagonal, we need a different set of ranges, but the rules remain the same:

    lena[range(xmax-1,-1,-1), range(ymax)] = 0

    At the final stage, we produce the following picture with the diagonals crossed out:

We specified different ranges for the x values and y values. These ranges were used to index the Lena array. Fancy indexing is done based on an internal NumPy iterator object. The following three steps are performed:

  1. The iterator object is created.
  2. The iterator object gets bound to the array.
  3. Array elements are accessed via the iterator.
主站蜘蛛池模板: 哈巴河县| 舟山市| 即墨市| 茂名市| 石嘴山市| 津南区| 南部县| 苏尼特左旗| 古浪县| 闵行区| 崇信县| 平山县| 上高县| 资兴市| 大埔县| 汉源县| 鹤壁市| 武邑县| 壶关县| 民勤县| 丹棱县| 泊头市| 景洪市| 遂宁市| 遂川县| 陈巴尔虎旗| 抚顺市| 龙游县| 江西省| 洪江市| 波密县| 克山县| 龙胜| 苗栗县| 临漳县| 河北省| 英吉沙县| 罗源县| 抚松县| 太仆寺旗| 鞍山市|