- Python Data Analysis
- Ivan Idris
- 122字
- 2021-08-05 17:31:52
Indexing NumPy arrays with Booleans
Boolean indexing is indexing based on a Boolean array and falls in the family of fancy indexing. Since Boolean indexing is a kind of fancy indexing, the way it works is essentially the same.
The following is the code for this segment (refer to boolean_indexing.py
in this book's code bundle):
import scipy.misc import matplotlib.pyplot as plt import numpy as np lena = scipy.misc.lena() def get_indices(size): arr = np.arange(size) return arr % 4 == 0 lena1 = lena.copy() xindices = get_indices(lena.shape[0]) yindices = get_indices(lena.shape[1]) lena1[xindices, yindices] = 0 plt.subplot(211) plt.imshow(lena1) lena2 = lena.copy() lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 0 plt.subplot(212) plt.imshow(lena2) plt.show()
The preceding code implies that indexing occurs with the aid of a special iterator object. The following steps will give you a brief explanation of the preceding code:
- Image with dots on the diagonal.
This is in some manner similar to the Fancy indexing section. This time we choose modulo 4 points on the diagonal of the picture:
def get_indices(size): arr = np.arange(size) return arr % 4 == 0
Then, we just use this selection and plot the points:
lena1 = lena.copy() xindices = get_indices(lena.shape[0]) yindices = get_indices(lena.shape[1]) lena1[xindices, yindices] = 0 plt.subplot(211) plt.imshow(lena1)
- Set to
0
based on value.Select array values between one quarter and three quarters of the maximum value and set them to
0
:lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 0
- The diagram with the two new pictures is presented as follows:
推薦閱讀
- Practical Data Wrangling
- 離散事件系統建模與仿真
- Apache Spark Deep Learning Cookbook
- Ceph:Designing and Implementing Scalable Storage Systems
- Troubleshooting OpenVPN
- 空間站多臂機器人運動控制研究
- Mastering pfSense
- R Data Analysis Projects
- 液壓機智能故障診斷方法集成技術
- Linux系統下C程序開發詳解
- Learning Apache Apex
- 青少年VEX IQ機器人實訓課程(初級)
- HBase Essentials
- 計算機辦公應用培訓教程
- Red Hat Enterprise Linux 5.0服務器構建與故障排除