import numpy as np
rand = np.random.RandomState(42)
x = rand.randint(100,size=10)
print(x)
[x[3],x[7],x[2]]
ind = [3,7,4]
x[ind]
ind = np.array([[3,7],[4,5]])
x[ind]
X = np.arange(12).reshape((3,4))
X
row = np.array([0,1,2])
col = np.array([2,1,3])
X[row,col]
X[row[:,np.newaxis],col]
row[:,np.newaxis] * col
print(X)
X[2,[2,0,1]]
X[1:,[2,0,1]]
mask = np.array([1,0,1,0],dtype=bool)
X[row[:,np.newaxis],mask]
mean = [0,0]
cov = [[1,2],[2,5]]
X = rand.multivariate_normal(mean,cov,100)
X.shape
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn;seaborn.set()
plt.scatter(X[:,0],X[:,1]);
indices = np.random.choice(X.shape[0],20,replace=False)
indices
selection = X[indices]
selection.shape
plt.scatter(X[:,0],X[:,1],alpha=0.3)
plt.scatter(selection[:,0],selection[:,1],facecolor='none',edgecolor='b',s=200);
x = np.arange(10)
i = np.array([2,1,8,4])
x[i] = 99
print(x)
x[i] -=10
print(x)
i = [2,3,3,4,4,4]
x = np.zeros(10)
np.add.at(x,i,1)
print(x)
np.random.seed(42)
x = np.random.randn(100)
bins = np.linspace(-5,5,20)
'''
counts = np.zeros_like(bins) #返回与给定数组形状和类型相同的零数组。
#为每个x找到合适的区间
i = np.searchsorted(bins,x)#查找应该插入元素以保持顺序的索引。
#为每个区间加上1
np.add.at(counts,i,1)
# 计数数组 counts 反映的是在每个区间中的点的个数,即直方图分布
plt.plot(bins,counts,linestyle='steps'); #画出结果
'''
plt.hist(x,bins,histtype='step');
print("NumPy routine:")
%timeit counts, edges = np.histogram(x, bins)
print("Custom routine:")
%timeit np.add.at(counts, np.searchsorted(bins, x), 1)
x = np.random.randn(1000000)
print("NumPy routine:")
%timeit counts, edges = np.histogram(x, bins)
print("Custom routine:")
%timeit np.add.at(counts, np.searchsorted(bins, x), 1)