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