- Python Data Analysis
- Ivan Idris
- 186字
- 2021-08-05 17:31:52
Indexing with a list of locations
Let's apply the ix_()
function to shuffle the Lena photo. The following is the code for this example without comments. The finished code for the recipe can be found in ix.py
in this book's code bundle:
import scipy.misc import matplotlib.pyplot as plt import numpy as np lena = scipy.misc.lena() xmax = lena.shape[0] ymax = lena.shape[1] def shuffle_indices(size): arr = np.arange(size) np.random.shuffle(arr) return arr xindices = shuffle_indices(xmax) np.testing.assert_equal(len(xindices), xmax) yindices = shuffle_indices(ymax) np.testing.assert_equal(len(yindices), ymax) plt.imshow(lena[np.ix_(xindices, yindices)]) plt.show()
This function produces a mesh from multiple sequences. We hand in parameters as one-dimensional sequences and the function gives back a tuple of NumPy arrays, for instance, as follows:
In : ix_([0,1], [2,3]) Out: (array([[0],[1]]), array([[2, 3]]))
To index the NumPy array with a list of locations, execute the following steps:
- Shuffle array indices.
Make an array with random index numbers with the
shuffle()
function of thenumpy.random
subpackage. The function modifies the array in place.def shuffle_indices(size): arr = np.arange(size) np.random.shuffle(arr) return arr
- Plot the shuffled indices, as shown in the following code:
plt.imshow(lena[np.ix_(xindices, yindices)])
- What we obtain is a totally scrambled Lena:
推薦閱讀
- Visualforce Development Cookbook(Second Edition)
- 精通MATLAB神經(jīng)網(wǎng)絡(luò)
- 實(shí)時(shí)流計(jì)算系統(tǒng)設(shè)計(jì)與實(shí)現(xiàn)
- 機(jī)器學(xué)習(xí)與大數(shù)據(jù)技術(shù)
- 讓每張照片都成為佳作的Photoshop后期技法
- STM32嵌入式微控制器快速上手
- 運(yùn)動(dòng)控制器與交流伺服系統(tǒng)的調(diào)試和應(yīng)用
- Linux嵌入式系統(tǒng)開(kāi)發(fā)
- Python文本分析
- 未來(lái)學(xué)徒:讀懂人工智能飛馳時(shí)代
- 傳感器原理與工程應(yīng)用
- 人工智能:智能人機(jī)交互
- 計(jì)算機(jī)組裝與維修實(shí)訓(xùn)
- Windows 7來(lái)了
- 分布式Java應(yīng)用