原英文文档
encoding:utf-8
1.导入包
import numpy as np
2.显示版本,打印配置信息
print(np.__version__)
print(np.show_config())
3.创建一个size为10值为0的vector
print(np.zeros(10))
4.获取某个函数的帮助文档
print(np.info(np.add))
5.创建一个值都为0的vector,第5个值为1
Z = np.zeros(10)
Z[4] = 1
print(Z)
6.创建一个值得范围为10-49的向量
Z = np.arange(10,50)
print(Z)
7.翻转一个vector
Z = np.arange(50)
print(Z[::-1])
8.创建一个3*3的矩阵,值的范围从0-8
Z= np.arange(9).reshape((3,3))
print(Z)
9.找到非0数值的索引
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
10.创建一个3*3的单位矩阵
Z = np.eye(3,3)
print(Z)
11.创建一个333的随机数组
Z= np.random.random((10,10))
print(Z)
12.创建一个10*10的随机数组,并找到最大最小值
Z = np.random.random((10,10))
Zmin,Zmax = Z.min(),Z.max()
print(Zmin,Zmax)
13.创建一个长度的30的随机数据,并计算平均值
Z = np.random.random(30)
Zmean = Z.mean()
print(Zmean)
14.创建一个2维数组,border为1,里面为0
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
15.下面表达式的结果
print(0*np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(0.3 == 3*0.1)
16创建一个5*5的矩阵,1,2,3,4正好在对角线下面
Z = np.diag(1+np.arange(4),k=-1)
print(Z)
17.创建一个8*8的矩阵,棋盘形式填充
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
18.考虑一个(6,7,8)形状数组,第100个元素的索引(x,y,z)是多少?
print(np.unravel_index(100,(6,7,8)))
19.用tile函数创建一个8*8的棋盘矩阵
Z = np.tile(np.array([[0,1],[1,0]]),(4,4))
print(Z)
20.归一化一个5*5的随机数组
Z = np.random.random((5,5))
Zmin,Zmax = Z.min(),Z.max()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)
21.创建一个自定义的dtype,它将颜色描述为四个无符号字节(RGBA)
color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])
print(color)
22.53矩阵乘以32矩阵
Z = np.dot(np.ones((5,3)),np.ones((3,2)))
print(Z)
23.给定一个1D阵列,3到8之间的元素置为相反数
Z = np.arange(11)
Z[(Z > 3) & (Z <8)] *= -1
print(Z)
24.下面脚本的输出
print(sum(np.arange(5),-1))
print(np.sum(np.arange(5),-1))
25.以下表达式哪个是合法的?
Z = np.arange(10)
Z**Z
2 << Z >>2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
26.以下表达式的运行结果
np.array(0) // np.array(0)
np.array(0) // np.array(0.)
np.array(0) / np.array(0)
np.array(0) / np.array(0.)
27.数组的四舍五入
Z = np.random.uniform(-10,+10,10)
print (np.trunc(Z + np.copysign(0.5, Z)))
28.用5中不同的方法提取数组的整数部分
Z = np.random.uniform(0,10,10)
print(Z - Z%1)
print(np.floor(Z))
print(np.ceil(Z - 1))
print(Z.astype(np.int32))
print(np.trunc(Z))
29.创建一个5x5矩阵,行值范围从0到4
Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)
30.考虑一个生成函数,生成10个整数,并使用它生成一个数组
def generate():
for x in xrange(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)
31.创建一个大小为10的向量,值为0到1,不包含0和1
Z = np.linspace(0,1,12,endpoint=True)[1:-1]
print(Z)
32.创建一个随机向量并排序
Z = np.random.random(10)
Z.sort()
print(Z)
33.如果比np.sum更快的求数组的和
Z = np.arange(10)
print(np.add.reduce(Z))
34.判断两个随机数组是否相等
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
equal = np.allclose(A,B)
print(equal)
35.使数组只读
Z = np.zeros(10)
Z.flags.writeable = False
Z[5] = 1
36.考虑一个代表笛卡尔坐标的随机10x2矩阵,将其转换为极坐标
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)
37.创建大小为10的随机向量,并将最大值替换为0
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)
38.创建一个结构化数组,使x,y的坐标覆盖 [0,1]x[0,1]区域
Z = np.zeros((10,10), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10),
np.linspace(0,1,10))
print(Z)
39.给定两个数组X和Y构造Cauchy矩阵C (Cij = 1/(xi - yj))
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X,Y)
print(np.linalg.det(C))
40.打印每个numpy标量类型的最小和最大可表示值
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
41.如何打印一个数组的所有元素
np.set_printoptions(threshold=np.nan)
Z = np.zeros((25,25))
print(Z)
42.找到和另一个数组最接近的值
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
43.构建一个结构化数组,表示position(x,y)和color(r,g,b)
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
print(Z)
44.构建一个(10,2)的随机向量表示坐标,计算点与点之间的距离
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
# Much faster with scipy
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
45.怎样把一个整型数组转换成浮点型
Z = np.arange(10, dtype=np.int32)
Z = Z.astype(np.float32, copy=False)
46.怎样读取一个文件
'''
File content:
-------------
1,2,3,4,5
6,,,7,8
,,9,10,11
-------------
'''
Z = np.genfromtxt("missing.dat", delimiter=",")
47.numpy数组的枚举是什么?
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index)
print(index, Z[index])
48.生成一个通用的2D高斯分布数组
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
49.如何随机p个元素放置在2D数组中?
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)
50.减去矩阵每行的平均值
Z = np.random.rand(5,10)
Y = Z - Z.mean(axis=1,keepdims = True)
print(Z)
print(Y)
51.如何根据第n列排序数组
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
52.如何判断给定的2D数组是否具有空列?
Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
53.从数组中的给定值中找到最近的值
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
54.创建一个具有name属性的数组类
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
55.考虑一个1-D向量,如何向由第二个向量索引的每个元素添加1(小心重复索引)
Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)
56.如何基于索引列表(I)将向量(X)的元素累加到数组(F)
X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,weights = X)
print(F)
57.考虑一个(w,h,3)的图像,数据类型为unit8,计算色彩个数
w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(n)
58.考虑一个四维数组,如何一次得到最后两轴的和?
A = np.random.randint(0,10,(3,4,3,4))
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum)
59.考虑一维向量D,如何使用描述子集索引的相同大小的向量S来计算D的子集的平均值?
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S,weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)
60.如何计算对角线元素点乘
A = np.random.randint(0,10,(3,3))
B = np.random.randint(0,10,(3,3))
# Slow version
print(np.diag(np.dot(A, B)))
# Fast version
print(np.sum(A * B.T, axis=1))
# Faster version
print(np.einsum("ij,ji->i", A, B))