Numpy 基础经典练习题100道---中英双语

1. Import the numpy package under the name np (★☆☆)')

导入numpy模块,设置别称为np

import numpy as np

2. Print the numpy version and the configuration (★☆☆)')

显示numpy的版本号和配置文件

print(np.__version__)
np.show_config()

3. Create a null vector of size 10 (★☆☆)')

创建一个大小为10的空向量

# np.empty 构造一个大小为 shape 的未初始化数组,
# np.zeros 构造一个大小为 shape 的全0数组,
# np.ones 构造一个大小为 shape 的全1数组,
# np.ones 构造一个大小为 shape 的全1数组,
# np.full 构造一个大小为 shape 的用指定值填满的数组,
#
print(np.empty(10))
print(np.zeros(10))
print(np.full((2,3),5.0))

4. How to find the memory size of any array (★☆☆)')

查看数组占用内存大小

# hint 每个元素点用内存大小乘以元素个数

sample4_1 = np.empty((3, 2), np.uint32)
sample4_2 = np.empty((3, 2), np.float16)
print(sample4_1.itemsize * sample4_1.size)
print(sample4_2.itemsize * sample4_2.size)

5. How to get the documentation of the numpy add function from the command line? (★☆☆)')

查看numpy中add函数的用法

# hint 使用 np.info函数可以查询函数,类,模块的文档

np.info(np.add)

6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)')

创建一个大小为10的空向量,将第5个值设为1

sample = np.zeros(10)
sample[4] = 1
print(sample)

7. Create a vector with values ranging from 10 to 49 (★☆☆)')

用10到49的序列构建一个向量

sample2 = np.arange(10, 50) # arange 同样不包含stop的值。
print(sample2)

8. Reverse a vector (first element becomes last) (★☆☆)')

将一个数组变换倒序(最后一个元素成为第一个元素)

# hint  这里是python的切片[起:止:间隔]
# print(np.arange(10)[::1]) 正常输出
# print(np.arange(10)[0::1]) 与上面相同
# print(np.arange(10)[1::1]) 从第二个元素开始到最后一个
# print(np.arange(10)[1::-1]) 从第二个元素开始倒序输出
# print(np.arange(10)[::-2]) 从最后一个元素起,间隔一个输出

print(np.arange(10))
print(np.arange(10)[::-1])

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)')

用0-8这9个数构造一个3x3大小的矩阵

# reshape 可以允许有一个参数为-1 ,系统会依据元素个数进行换算
sample3 = np.arange(9).reshape((3, -1))
print(sample3)

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)')

从数组[1,2,0,0,4,0]中找出非0元素的下标

print(np.nonzero([1, 2, 0, 0, 4, 0]))

11. Create a 3x3 identity matrix (★☆☆)')

创建3x3的对角矩阵

# identity 只能创建方阵,eye要灵活一些,可以创建NxM的矩阵,也可以控制对角线的位置
print(np.identity(3))

print(np.eye(3,3,0))  #默认第一个和第二个参数相等,第三个参数为对角线位置

12. Create a 3x3x3 array with random values (★☆☆)')

用随机数创建一个3x3x3的矩阵

print(np.random.random((3, 3, 3)))

13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)')

创建一个10x10的随机数矩阵,并找到最大值和最小值

sample13 = np.random.random((10, 10))
print(sample13)
print(sample13.max(), np.min(sample13))

14. Create a random vector of size 30 and find the mean value (★☆☆)')

创建一个大小为30的数组,并计算其算术平均值

# mean计算算术平均值 average 计算加权平均值np.average(np.arange(1, 11) , weights=np.arange(10, 0, -1))

print(np.random.random(30).mean())

```python
## 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)')
## 创建一个二维数组,边为1,其余为0 

```python
# hint [1:-1,1:-1]表示切出了芯。
sample15 = np.ones((5, 5))
print(sample15)
sample15[1:-1, 1:-1] = 0
print(sample15)

16. How to add a border (filled with 0s) around an existing array? (★☆☆)')

扩展给定数组的边界

# hint pad 函数 有几种mode
sample16 = np.ones((4,4))
print(np.pad(sample16, 1, mode='constant', constant_values=0))

17. What is the result of the following expression? (★☆☆)')

指出下列表达式的结果是什么?

# nan的意思是Not a Number nan的类型是float64
print(0 * np.nan)  # nan  有nan参与的运算, 其结果也一定是nan
print(np.nan - np.nan) # nan
print(np.nan == np.nan) # False nan不是数,所以无法进行比较运算
print(np.nan > np.nan) # False
print(np.nan in {np.nan}) # True  nan在nan的字典中
print(0.3 == 3 * 0.1) # False  浮点数可以比大小,但相等要用math.isclose比较
import math
print(math.isclose(0.3, 3 * 0.1)) # True

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)')

用1,2,3,4做为对角线的下移一行,来创建5x5的矩阵

# hint diag函数的第二个参数指定对角线的位置
print(np.diag([1, 2, 3, 4], -1))

19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)')

创建一个类似国际象棋棋盘的8x8的矩阵

sample19 = np.zeros((8, 8))

sample19[::2, ::2] = 1
sample19[1::2, 1::2] = 1
print(sample19)

20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?(★☆☆)')

对一个6x7x8的数组,找出第100个元素的下标

# hint unravel 这个函数非常难以理解,特别是第一个参数为向量时。
print(np.unravel_index(100, (6, 7, 8)))

21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)')

使用tile函数创建一个棋盘

print(np.tile([[0, 1], [1, 0]], (4, 4)))

22. Normalize a 5x5 random matrix (★☆☆)')

归一化一个5x5的随机矩阵

sample22 = np.random.random((5,5))*10
print(sample22)
print((sample22 - sample22.mean()) / sample22.std()) # std 计算均方差

23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)')

自定义一个用 unsigned bytes 表示RGBA颜色的dtype类型

# hint np.dtype
print(np.dtype([('R', np.ubyte), ('G', np.ubyte), ('B', np.ubyte), ('A', np.ubyte)]))

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)')

计算5x3和3x2矩阵的内积(点乘)

# multiply(*) dot(@) matmul 这三个函数注意区分
sample24_1 = np.random.randint(0, 9, (5, 3))
sample24_2= np.random.randint(0, 9, (3, 2))
print(np.dot(sample24_1,sample24_2))
print(sample24_1 @ sample24_2)

25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)')

反转一维数组中大于3小于8的所有元素

sample25 = np.arange(2, 12)
sample25[(sample25 >3) & (sample25 <8)] *= -1 # 使用& 表示 and
print(sample25)

26. What is the output of the following script? (★☆☆)')

指出下列程序的输出?

#  Author: Jake VanderPlas

 print(sum(range(5),-1))
 from numpy import *
 print(sum(range(5),-1))

print(sum(range(5), -1)) # sum(range(5)) + (-1)

print(np.sum(range(5),-1)) # 在选定的轴上执行求和。如果是默认值(axis=None),就会在所有的轴上执行求和。axis可以是负数,负数的话就代表倒着数的意思,和列表索引访问差不多(N表示第N个,-N表示倒数第N个(没有倒数第0个))

27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)')

对于整数向量,下面的哪些表达式是合法的?

Z = np.random.choice(10, 4)

Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z  # 使用 any 或 all

28. What are the result of the following expressions?(★☆☆)')

下面的表达式的结果是?

python np.array(0) / np.array(0) # 0 除法 np.array(0) // np.array(0) # 0 除法 np.array([np.nan]).astype(int).astype(float)

29. How to round away from zero a float array ? (★☆☆)')

对于浮点数数组取整??

# (**hint**: np.random.uniform(给定形状产生随机数组), np.copysign, np.ceil, np.abs)
sample29 =np.random.uniform(-10,10 ,10)
print(sample29)
print(np.ceil(np.copysign(sample29,np.ones(10))))
print(np.ceil(np.abs(sample29)))

30. How to find common values between two arrays? (★☆☆)')

查找两个数组的交集?

print(np.intersect1d([1, 2, 3], [4, 2, 1]))

31. How to ignore all numpy warnings (not recommended)? (★☆☆)')

忽略numpy的警告?

defaults = np.seterr(all="ignore")

32. Is the following expressions true? (★☆☆)')

下列表达式结果为真么? (★☆☆)')

# np.sqrt(-1)  # 出现警告
np.emath.sqrt(-1) #emath自动域数学函数 扩展到复数

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)')

获取今天,昨天,明天的日期?

# 从NumPy 1.7开始,有核心数组数据类型本身支持日期时间功能。 数据类型称为“datetime64”,因为“datetime”已被Python中包含的日期时间库占用。
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(yesterday,today,tomorrow)

34. How to get all the dates corresponding to the month of July 2016? (★★☆)')

获取2016年7月的所有日期?

Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)')

避免复制操作来计算 ((A+B)*(-A/2)) ?

A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
print(np.multiply(A, B, out=A))

sample35_1 = np.arange(0, 10).reshape(2, 5)
sample35_2 = np.arange(10, 0, -1).reshape(2, 5)
sample35_r = np.empty((2, 5))
print(sample35_1)
print(sample35_2)

np.multiply(np.add(sample35_1, sample35_2), np.divide(np.negative(sample35_1), 2), out=sample35_r)

print(sample35_r)

36. Extract the integer part of a random array using 5 different methods (★★☆)')

用五种方法抽取随机矩阵的整数部分(只想到一种)

Z = np.random.uniform(0,10,(10,10))
print(Z-Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)')

创建一个5x5每行为0到4的矩阵

print(np.tile(np.arange(5), (5, 1)))

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)')

使用生成器创建一个大小为10的数组

def gen(num):
    seed = 0
    for i in range(num):
        yield seed
        seed +=4
    return seed
print(np.array([x for x in gen(10)]))

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)')

创建一个大小为10的数组,值为0到1之间,不包含0和1

print(np.linspace(0, 1, 11, False)[1:])

40. Create a random vector of size 10 and sort it (★★☆)')

创建一个大小为10的数组并排序

sample40 = np.random.randint(0, 9, 10)
sample40.sort()
print(sample40)

41. How to sum a small array faster than np.sum? (★★☆)')

对一个小数组用比np.sum快的方法求和?

# hint

sample41 = np.arange(0,20)

print(np.add.reduce(sample41))

42. Consider two random array A and B, check if they are equal (★★☆)')

比较两个随机数组是否相等

A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)

equal = np.allclose(A,B) #默认在1e-05的误差范围内,比较两个array是不是每一元素都相等
print(equal)

equal = np.array_equal(A,B) # 比较两个数组是否相等
print(equal)

43. Make an array immutable (read-only) (★★☆)')

创建一个不可变数组(只读)

Z = np.zeros(10)
Z.flags.writeable = False

用户可以更改 WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED 这四个标志 Z[0] =1 # 报错:ValueError: assignment destination is read-only

44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)')

创建一个大小为10x2的矩阵来代表笛卡儿坐标,并转

cart = np.random.random((10, 2))
#
# vstack hstack column_stack
polar = np.column_stack((np.sqrt(np.add.reduce(np.square(cart), axis=1)), np.arctan(np.divide.reduce(cart, axis=1))))
print(cart, '\n\n', polar)

Z = cart
X, Y = Z[:, 0], Z[:, 1]
R = np.sqrt(X ** 2 + Y ** 2)
T = np.arctan2(Y, X) # arctan2 和 archtan的区别
print(np.column_stack((R, T)))

45. Create a random vector of size 10 and replace the maximum value by 0 (★★☆)')

创建一个大小为10的数组并把最大值设为0

sample45 = np.random.uniform(0,9,10)
print(sample45)
sample45[sample45.argmax()] =0
print(sample45)

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area')

创建一个xy的数组结构,包含[0,1]x[

# hint np.meshgrid 这个函数没有理解
x = y = 5
nx = np.linspace(0, 1, x)
ny = np.linspace(0, 1, y)
xx, yy = np.meshgrid(nx, ny)
print(xx,yy)

Z = np.zeros((5,5),[('x',float),('y',float)])
Z['x'],Z['y'] = np.meshgrid(np.linspace(0,1,5),np.linspace(0,1,5))
print(Z)

47. Given two arrays, X and Y, construct the Cauchy matrix(柯西矩阵) C (Cij =1/(xi - yj))(★☆☆)')

给定array X 和 Y, 构造柯西矩阵C (★☆☆)')

X = np.arange(3)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))

48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)')

显示机器能处理的数值的范围

print(np.iinfo(np.int64))
print(np.iinfo(np.int32))
print(np.iinfo(np.uint16))
print(np.finfo(np.float64))
print(np.finfo(np.float16))

49. How to print all the values of an array? (★★☆)')

显示array中所有的值

print(np.eye(10))
np.set_printoptions(threshold=100)
print(np.eye(40))

50. How to find the closest value (to a given scalar) in a vector? (★★☆)')

如何在向量中找到指定范围的最近值?

sample50 = np.random.rand(4, 3) * 10
print(sample50)
print(np.argmin(sample50))
print(np.argmin(sample50, axis=0))
print(np.argmin(sample50, axis=1))
print(np.unravel_index(np.argmin(sample50), sample50.shape))

Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v).argmin())
print(Z[index])

51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)')

构建一个代表位置 (x,y) 和 颜色 (r,g,b)的矩阵

mydtype = np.dtype([('xy',[('x', np.int64), ('y', np.int64)]), ('color',[('r', np.int16), ('g', np.int16), ('b', np.int16)])])

print(np.ones((3, 2), mydtype))

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)')

用一个100*2的随机向量来表示坐标,计算点到点的距离

Z = np.random.random((100,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
#  使用scipy处理速度快
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial

Z = np.random.random((100,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)

53. How to convert a float (32 bits) array into an integer (32 bits) in place?(★☆☆)')

如何把一个浮点数组直接转换

print((np.random.rand(20)*10).astype(np.int32,copy=False))

54. How to read the following file? (★★☆)')

从文本文件中读取数据? (★★☆)')

txt 1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11

from io import StringIO

s = StringIO("""1, 2, 3, 4, 5\n
                6,  ,  , 7, 8\n
                ,  , 9,10,11\n""") # 模拟文件
print(np.genfromtxt(s,delimiter=','))

55. What is the equivalent of enumerate for numpy arrays? (★★☆)')

矩阵的坐标

for index ,x in np.ndenumerate(np.eye(3)):
    print(index,x)

for index in np.ndindex(3,3):
    print(index)

56. Generate a generic 2D Gaussian-like array (★★☆)')

生成二维高斯分布

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)))

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax= fig.add_subplot(1, 3, 1, projection='3d')
suf=ax.plot_surface(X, Y, G, rstride=1, cstride=1, cmap='rainbow')
fig.colorbar(suf,shrink=0.5, aspect=5)
plt.subplot(132)
suf1 =plt.contourf(X,Y,G,8, alpha=.75, cmap='rainbow')
fig.colorbar(suf1,shrink=0.5, aspect=5)
# plt.show()

57. How to randomly place p elements in a 2D array? (★★☆)')

将元素P随机的放入二维数组中

sample57 = np.ones((3, 10))
print(sample57)
np.put(sample57, np.arange(0, sample57.size), np.random.choice(100, sample57.size))
print(sample57)

58. Subtract the mean of each row of a matrix (★★☆)')

矩阵的第一行减去算术平均值

sample58 = np.random.rand(3,3)*10
print(sample58)
print(np.subtract(sample58,np.mean(sample58,axis=1,keepdims=True)))

59. How to sort an array by the nth column? (★★☆)')

把数组按第n列排序?

sample59 = np.random.randint(0, 9, (3, 5))
print(sample59)
print(np.sort(sample59, axis=0))  # 全部都排序
print(np.argsort(sample59, axis=0))  # 给出的是位置

print(sample59[sample59[:, 1].argsort()])  # 按第二列排序

60. How to tell if a given 2D array has null columns? (★★☆)')

如何判断一个二维数组有全为0的列?

Z= np.random.randint(0,3,(3,20))
print('\n',Z)
print((~Z.any(axis=0)).any())

61. Find the nearest value from a given value in an array (★★☆)')

从数组中找出给定值的最近似值

Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)

62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)')

使用迭代器计算1x3和3x1的数组的和?

A = np.arange(3).reshape(3, 1)
B = np.arange(3).reshape(1, 3)
it = np.nditer([A, B, None])  # 多维数组的迭代
for x, y, z in it:
    z[...] = x + y
print(it.operands[2])

63. Create an array class that has a name attribute (★★☆)')

创建一个有名字的数组类 (★★☆)')

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)

64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)')

对一个给定数组,如何按第二个数组表示的索引位置将对应的元素+1,注意重复的位置要重复加1?

# Author: Brett Olsen

Z = np.ones(10)
Z1 = np.ones(10)
I=I1 = np.random.randint(0, len(Z), 20)
print(I)

Z += np.bincount(I, minlength=len(Z))
print(Z)

# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z1, I1, 1)
print(Z1)

```python
## 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)')
## 如何基于索引列表I,将向量X的各元素累加到数组F上? 

```python
#
# Author: Alan G Isaac

X = [1,2,3,4,5,6]
I = [0,0,0,1,1,2] # 比重
F = np.bincount(I,X)
print(F)

66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)')

对一个(w,h,3)表示的图像,如何计算不重复的颜色

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] # 三个颜色
print(F)
n = len((np.unique(F)))
print(np.unique(I))

67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)')

对一个四维数组,如何计算最后两个轴上的元素和?

A = np.random.randint(0, 10, (3, 4, 5, 6))
print(A.sum(axis=(-2, -1)))

# 方法二

print(A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1))  # 把A变为(3,4,-1)把最后两个轴合并

68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)')

对一个一维向量D,如何按按权重S来计算算术平均值?

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)

69. How to get the diagonal of a dot product? (★★★)')

获取点积的对角矩阵?

# Author: Mathieu Blondel

A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
print()
# 慢
print((np.diag(np.dot(A, B))))

# 快
print(np.sum(A * B.T, axis=1))

# 最快
print(np.einsum("ij,ji->i", A, B))

70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)')

将向量[1,2,3,4,5],元素中间插入3个0,形成新的数组

sample70 = np.array([1,2,3,4,5])
result = np.zeros ((sample70.size-1)*4+1,dtype=np.int)
result[0::4] = sample70
print(result)

71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)')

将一个5x5x3的数组与5x5的数组相乘?

A = np.random.choice(10, (5, 5, 3))
B = np.random.choice(10, (5, 5))
print(A * B[..., np.newaxis])

72. How to swap two rows of an array? (★★★)')

交换数组的两行?

# hint 这里还是索引选择

sample72 = np.random.choice(100,16).reshape(4,-1)
print(sample72)
sample72[[1,2],...]=sample72[[2,1],...]
print(sample72)

73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)')

使用10个三元数的集合描述10个三角形,找出组成这些三角形边的集合

# Author: Nicolas P. Rougier

faces = np.random.randint(0, 100, (10, 3))
F = np.roll(faces.repeat(2, axis=1), -1, axis=1)  # roll 元素在某一轴方向滚动
F = F.reshape(len(F) * 3, 2)
F = np.sort(F, axis=1)
G = F.view(dtype=[('p0', F.dtype), ('p1', F.dtype)])
G = np.unique(G)
print(G)

74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)')

依据bincount的结果来构造一个数组,使得np.bincount(A)==C?

# bincount 是计算一个整数数组中各元素出现的次数。结果按最大元素的序列来表示。
C = np.array([1, 2, 3, 0, 5])
res = np.array([], dtype=int)
for x in C:
    res = np.append(res, np.ones(x) * (x - 1))
print(res.astype(int))

75. How to compute averages using a sliding window over an array? (★★★)')

使用滑动窗口计算数组平均值?

# Author: Jaime Fernández del Río

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))

76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)')

给定一维数组Z,构造一个二维数组,其第一行为Z[0],Z[1],Z[2]),下一行依次偏移1位,最后一行为(Z[-3],Z[-2],Z[-1])

# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks

def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)

77. How to negate a boolean, or to change the sign of a float inplace? (★★★)')

改变浮点数的符号?

# Author: Nathaniel J. Smith

Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)

Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)

78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)')

用两个点集来描述的一组线和一个点P,如何计算P点到这些线的距离?

A = np.array([[1, 2], [1, 2], [1, 3], [1, 2]])
B = np.array([[2, 1], [2, 2], [3, 1], [3, 2]])
C = np.array([1.2, 1.2])

print(np.abs(np.cross(A - C, B - C, axis=1)) / np.linalg.norm(A - B, axis=1))

79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)')

现有由两个点集P0P1来表示的二维平面的上的线以及一个点集P,计算每个点到每个线的距离? (★★★)')

# Author: Italmassov Kuanysh

def distance(P0, P1, p):
    T = P1 - P0
    L = (T ** 2).sum(axis=1)
    U = -((P0[:, 0] - p[..., 0]) * T[:, 0] + (P0[:, 1] - p[..., 1]) * T[:, 1]) / L
    U = U.reshape(len(U), 1)
    D = P0 + U * T - p
    return np.sqrt((D ** 2).sum(axis=1))
P0 = np.random.uniform(-10, 10, (10, 2))
P1 = np.random.uniform(-10, 10, (10, 2))
p = np.random.uniform(-10, 10, (10, 2))
print(np.array([distance(P0, P1, p_i) for p_i in p]))

80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)')

对任意的一个数组,编写一个函数,以一个给定的元素为中心,从数组中抽取一个固定大小的子矩阵(如果需要的话,使用固定的值进行填充)

# Author: Nicolas Rougier

Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill  = 0
position = (1,1)

R = np.ones(shape, dtype=Z.dtype)*fill
P  = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)

R_start = np.zeros((len(shape),)).astype(int)
R_stop  = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop  = (P+Rs//2)+Rs%2

R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()

r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
print(r)
R[r] = Z[z]
print(Z)
print(R)

81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)')

对于数组Z=[1,2,3,4,5,6,7,8,9,10,11,12,13,14],如何生成新的数组[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],...,[11,12,13,14]]?

Z = np.arange(1, 15, dtype=np.uint32)
R = np.lib.stride_tricks.as_strided(Z, (11, 4), (4, 4))
print(R)

# 我的做法,1.16 不支持生成器

for i in np.arange(Z.size - 3):
    R = np.vstack([R, Z[i:i + 4]])

# R =np.vstack((Z[i:i + 4] for i in np.arange(Z.size - 3)))
print(R)

82. Compute a matrix rank (★★★)')

计算矩阵的秩

Z = np.random.uniform(0, 1, (1000, 1000))
U, S, V = np.linalg.svd(Z)  # Singular Value Decomposition 奇异值分解
# print(U,S,V)
rank = np.sum(S > 1e-10)
print(rank)

83. How to find the most frequent value in an array?★)')

找到矩阵中出现频率最高

sample83 = np.random.randint(0,5,10)
print(sample83)
print(np.bincount(sample83))
print(np.bincount(sample83).argmax())

84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)')

从一个10x10矩阵中抽取出所有相邻的3x3矩阵

sample84 = np.random.randint(0, 10, (5, 5))
Z = sample84
n = 3

# 我的做法
print(sample84)
for i in range(sample84.shape[0] - n + 1):
    for j in range(sample84.shape[0] - n + 1):
        print(i * 10 + j, sample84[i:i + 3, j:j + 3])

# 答案
print(Z)
i = 1 + (Z.shape[0] - 3)
j = 1 + (Z.shape[1] - 3)
C = np.lib.stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)

85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)')

构造一个二维数组的子类,使得Z[i,j]=Z[j,i]

class Symtric(np.ndarray):
    def __setitem__(self, key, value):
        i, j = key
        super(Symtric, self).__setitem__((i, j), value)
        super(Symtric, self).__setitem__((j, i), value)
def symetric(Z):
    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symtric)
S = symetric(np.random.randint(0, 10, (5, 5)))
S[0, 0] = 42
print(S)

86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)')

现有大小为(n,n)的矩阵集合和大小为(n,1)的向量集合,如何计算张量乘法

p, n = 10, 20
M = np.ones((p, n, n))
V = np.ones((p, n, 1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)

87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)')

给定一个16x16的矩阵,对其中4x4的块进行求和?

# Author: Robert Kern

Z = np.random.choice(100,(16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
                    np.arange(0, Z.shape[1], k), axis=1)
print(S)

88. How to implement the Game of Life using numpy arrays? (★★★)')

使用数组实现生命游戏?

#
# 1. 每个细胞的状态由该细胞及周围八个细胞上一次的状态所决定;
# 2. 如果一个细胞周围有3个细胞为生,则该细胞为生,即该细胞若原先为死,则转为生,若原先为生,则保持不变;
# 3. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;
# 4. 在其它情况下,该细胞为死,即该细胞若原先为生,则转为死,若原先为死,则保持不变
#
# Author: Nicolas Rougier

def iterate(Z):
    # Count neighbours
    N = (Z[0:-2, 0:-2] + Z[0:-2, 1:-1] + Z[0:-2, 2:] +
         Z[1:-1, 0:-2] + Z[1:-1, 2:] +
         Z[2:, 0:-2] + Z[2:, 1:-1] + Z[2:, 2:])
    # # Apply rules
    birth = (N == 3)
    survive = ((N == 2) | (N == 3))
    Z[...] = 0
    Z[1:-1, 1:-1][birth | survive] = 1
    return Z
Z = np.random.randint(0, 2, (50, 50))
for i in range(100): Z = iterate(Z)
print(Z)

89. How to get the n largest values of an array (★★★)')

从数组中找出最大的n个值

Z = np.arange(50)
np.random.shuffle(Z)  # 将中元素顺序随机化
n = 5
# 慢
print(Z[np.argsort(Z)[-n:]])

# 快
print(Z[np.argpartition(-Z, n)[:n]])  # 最大的5个值是没有顺序的

90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)')

计算任意向量的笛卡尔积 (★★★)')

# Author: Stefan Van der Walt
def cartesian(arrays):
    arrays = [np.asarray(a) for a in arrays]
    shape = (len(x) for x in arrays)
    ix = np.indices(shape, dtype=int)
    ix = ix.reshape(len(arrays), -1).T

    for n, arr in enumerate(arrays):
        ix[:, n] = arrays[n][ix[:, n]]
    return ix
print(cartesian(([1, 2, 3], [4, 5], [6, 7])))

91. How to create a record array from a regular array? (★★★)')

从常规数组创建结构化数组?

Z = np.array([("Hello", 2.5, 3),
              ("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T, names='列1,列2,列3', formats='S8,f8,i8')
print(R)

92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)')

用三种方法计算一个大型数组中每个元素的立方

Z = np.random.choice(100,10000)
print(Z)
print(np.power(Z,3))
print(Z**3)
print(Z*Z*Z)
print(np.einsum('i,i,i->i',Z,Z,Z))

93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)')

给定一个8X3的数组A和一个2X2的数组B,从A中找出满足条件的行,条件是B中每一行都有元素出现在A中这一行中?

# Author: Gabe Schwartz

A = np.random.randint(0,5,(8,3))
B = np.array([[1,1],[1,1]])
C = (A[..., np.newaxis, np.newaxis] == B)

rows = np.where(C.any((3,1)).all(1))[0]
print('',A,'\n',B,'\n',rows)

94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)')

从一个10x3的数组中去除一行元素完全相同的行

# Author: Robert Kern
sample = np.arange(0, 10)
Z = np.random.choice(3, (10, 3))

U = Z[~(np.all(Z[..., 1:] == Z[..., :-1], axis=1))]  # 如果某行元素去除第一个元素形成的数组与排除最后一个元素形成的数组相同,则认为这行元素完全相同
print(U)

U = Z[Z.max(axis=-1) != Z.min(axis=-1), :]  # 仅限于Z是数值 如果一行元素最大值和最小值相等,则可以判定这行元素是完全相同的
print(U)

95. Convert a vector of ints into a matrix binary representation (★★★)')

把一个8位整型的一维数组表示为二进制的矩阵

I = np.array([0, 1, 2, 4, 8, 16, 32, 64, 128], dtype=np.uint8)

print(np.unpackbits(I[:, np.newaxis], axis=1))  # 将一个8位长整形元素展开成二进制形式

96. Given a two dimensional array, how to extract unique rows? (★★★)')

从二维矩阵中找出不同的行?

Z= np.random.randint(0,2,(6,3))
print(Z)
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize*Z.shape[1])))
_,idx = np.unique(T,return_index=True)

print(Z[idx])

uZ = np.unique(Z,axis=0)
print(uZ)

97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)')

给定数组A,B,使用函数einsum实现求和,矩阵相乘,内积和外积

#使用einsum函数,我们可以使用爱因斯坦求和约定(Einstein summation convention)在NumPy数组上指定操作
A = np.random.uniform(0,1,10) # 均匀分布
B = np.random.uniform(0,1,10) # 均匀分布

np.einsum('i->', A) # 求和
np.einsum('i,i->i', A, B) # 矩阵相乘
np.einsum('i,i', A, B)    # 内积
np.einsum('i,j->ij', A, B)    # 外积

98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples? (★★★)')

给定用两组向量(X,Y)描述的一条线,如何进行等距采样

phi = np.arange(0,10*np.pi,0.1)
a =1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5
r = np.zeros_like(x)
r[1:] = np.cumsum(dr)
print(r)
r_int = np.linspace(0, r.max(), 80)
x_int = np.interp(r_int, r, x)  #插值
y_int = np.interp(r_int, r, y)  #插值
plt.subplot(133)
plt.plot(x,y,x_int,y_int)

99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)')

给定整数n和一个二维数组X,从X中找出满足条件的行 指数为n的多项式分布

X = np.asarray([[1.0, 0.0, 3.0, 8.0],
                [2.0, 0.0, 1.0, 1.0],
                [1.5, 2.5, 1.0, 0.0]])

n = 4
print(np.mod(X, 1) == 0)
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)

# np.mod(X,1) 找出整数,
# axis =-1 表示最后一个维度
M = (X.sum(axis=-1) == n)
# 在最后一个维度上和为4
print(X[M])

100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means).

采用自助法计算给定一维数组在95%置信区间上的算术平均值

X = np.random.randn(100)  # 一维数组
N = 1000  # 自抽取数量

idx = np.random.randint(0, X.size, (N, X.size))  # 生成1000x100的随机索引数组
means = np.mean(X[idx], axis=1)  # 相当于对每一行的100个抽样值计算平均值,结果一个大小为1000的一维数组

confint = np.percentile(means, [2.5, 97.5])  # 计算百分位数 百分位数是统计中使用的度量,表示小于这个值的观察值占总数q的百分比
print(confint)

 

 

  • 24
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的学习日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值