Python-Numpy 学习笔记

python numpy学习笔记 numpy的主要数据对象是多维数组,其中包含相同类型的元素,通常是数字类型,每个元素都有一个索引。使用numpy前通常要导入包。 import numpy as np 目录类型维度创建运算索引和切片 类型 numpy的数组被称为ndarray。numpy.array只处理一维数组,而ndarray对象才提供更多功能。 a = np.array([[1, 2, 3], [4, 5, 6]]) type(a) # <class 'numpy.ndarray'> dtype属性可以获得元素的数 阅读详情

一个关于numpy的题库GitHub-Numpy100题,原文中 vector 解释为行向量(代码中使用 vector),matrix 解释为矩阵或数组(代码中使用 a 或 array),原作者对于 array 的使用在两种释义中切换,所以这个就看情况吧()。

基本设置

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

import numpy as np

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

print(np.__version__)
np.show_config()

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

np.info(np.function)  #np.function为 numpy 的指令

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

print(np.array(0) / np.array(0)) # 会有如下warning ↓
##RuntimeWarning: invalid value encountered in true_divide print(np.array(0) / np.array(0))

defaults = np.seterr(all="ignore") # 加上这句就没了
print(np.array(0) / np.array(0))

#### 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))
# 结果
Machine parameters for int64
---------------------------------------------------------------
min = -9223372036854775808
max = 9223372036854775807
---------------------------------------------------------------

Machine parameters for int32
---------------------------------------------------------------
min = -2147483648
max = 2147483647
---------------------------------------------------------------

Machine parameters for uint16
---------------------------------------------------------------
min = 0
max = 65535
---------------------------------------------------------------

Machine parameters for float64
---------------------------------------------------------------
precision =  15   resolution = 1.0000000000000001e-15
machep =    -52   eps =        2.2204460492503131e-16
negep =     -53   epsneg =     1.1102230246251565e-16
minexp =  -1022   tiny =       2.2250738585072014e-308
maxexp =   1024   max =        1.7976931348623157e+308
nexp =       11   min =        -max
---------------------------------------------------------------

Machine parameters for float16
---------------------------------------------------------------
precision =   3   resolution = 1.00040e-03
machep =    -10   eps =        9.76562e-04
negep =     -11   epsneg =     4.88281e-04
minexp =    -14   tiny =       6.10352e-05
maxexp =     16   max =        6.55040e+04
nexp =        5   min =        -max
---------------------------------------------------------------

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

print(np.eye(10))
np.set_printoptions(threshold=10)	# threshold调整显示最大值
print(np.eye(10))
#结果
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
 
[[1. 0. 0. ... 0. 0. 0.]
 [0. 1. 0. ... 0. 0. 0.]
 [0. 0. 1. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 1. 0. 0.]
 [0. 0. 0. ... 0. 1. 0.]
 [0. 0. 0. ... 0. 0. 1.]]

ndarray 的创建

指令功能
np.empty(shape[, dtype])创建一个大小为shape的随机数组(未初始化)
np.zeros(shape)创建一个全0数组
np.ones(shape)创建一个全1数组
np.eye(size)创建一个 size*size 的单位矩阵
np.full(shape,value)创建一个由value填满,大小为shape的数组
np.random.random(shape)创建一个由随机数填充的矩阵
np.array()用标准库array生成
np.arange(a,b[,c])创建一个从a到b(不包含b),步长为c的行向量
np.linspace(a, b[, c, endpoint=True, retstep=False, dtype=None])从a到b均匀选取c个值创建一个行向量,c默认为50,Endpoint取舍末端值,retstep展示步长
#例子
a1 = np.full((4,3),1)  #创建4行3列由1填充的矩阵(数组)
a2 = np.full_like(a1,3)  #创建一个与vector1相同但由3填充的矩阵(数组)

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

null_vector = np.zeros(10)
null_vector[4] = 1

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

vector = np.arange(10,50)

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

a = np.arange(9).reshape((3, 3))
# or
a = np.arange(9)
np.reshape(a, (3,3))

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

a = np.eye(3)

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

a = np.random.random((3,3,3))

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

a = np.eye(2)
print(np.tile(a,(4,4)))

np.tile 可以用于复制平移某一个矩阵,具体请自行查询

#### 37. Create a 5x5 matrix with row values ranging from 0 to 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 (★☆☆)

不太会捏,让俺再想想吧

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

print(np.linspace(0, 1, 11, endpoint = False)[1:])
#因为不包含首尾,所以用np.arange有点麻烦,还得自己算间隔(11等分有点难顶)

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

a = np.random.uniform(0,10,10)
a.sort()
print(a)

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

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

这个题有点像 MATLAB 里面生成一个 meshgrid 一样:

# 1
x = y = int(input('a number: '))
xx, yy = np.meshgrid(np.linspace(0,1,x), np.linspace(0,1,y))
xy = np.stack((xx,yy),axis=2)		# 也可以用np.dstack(),就不需要axis=2这个参数了
print(xy)
# 2
a = np.zeros((x,y),[('x',np.float),('y',np.float)])
a['x'],a['y'] = np.meshgrid(np.linspace(0,1,x),np.linspace(0,1,y))
print('\n\n',a)
# 结果
a number: 3
[[[0.  0. ]
  [0.5 0. ]
  [1.  0. ]]

 [[0.  0.5]
  [0.5 0.5]
  [1.  0.5]]

 [[0.  1. ]
  [0.5 1. ]
  [1.  1. ]]]


 [[(0. , 0. ) (0.5, 0. ) (1. , 0. )]
 [(0. , 0.5) (0.5, 0.5) (1. , 0.5)]
 [(0. , 1. ) (0.5, 1. ) (1. , 1. )]]

其中法2的a中元素的类型不是tuple,而是<class 'numpy.void'>。实际上为了方便索引和后续处理,第一种方法要更好一些。

如果单纯想将两个行向量组成类似坐标的形式,也可以这么做:

vector1 = np.arange(3)
vector2 = np.arange(5,8)
print(np.concatenate((vector1[None],vector2[None]),axis=0).T)
print(np.column_stack((vector1,vector2)))
# 结果
[[0 5]
 [1 6]
 [2 7]]

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

# 开始套娃
mydtype = np.dtype([('xy',[('x', np.int64), ('y', np.int64)]), ('rgb',[('r', np.int16), ('g', np.int16), ('b', np.int16)])])
print(np.ones((3, 2), mydtype))

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

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=','))

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

a = np.zeros((5,6))
p_num = int(input())			# 要插入的p的个数,因为这里要用来生成一个
								# 插入矩阵所以提前输入了这个;实际中如果
								# 已经有了p的矩阵,可以直接用 p.size 代替
p = np.random.random(p_num)
np.put(a,np.random.choice(a.size,p_num,replace=False),p)
								# np.put(a, ind, v[, mode=''])用数组v中
								# 的值替换数组a中索引为 ind 的元素,ind可
								# 以是一切合法的索引形式,包括布尔值的索引;
								# v也可以是多维的,如下被注释掉的一行
#np.put(a,np.random.choice(a.size,p_num,replace=False),p.reshape(2,int(p_num/2)))
								# choice(a, size=None, replace=True, p=None)
								# 用来随机抽取,replace=False意味着没有重复
print(a)
print(np.array(a.nonzero())[0,:].size)		# 用来检测是否将p全部插入
# 结果
10
[[0.91023252 0.67975792 0.         0.         0.         0.95960602]
 [0.         0.         0.         0.         0.37070113 0.34431715]
 [0.6080532  0.         0.         0.         0.72130095 0.        ]
 [0.         0.30608934 0.74424351 0.29370978 0.         0.        ]
 [0.         0.         0.         0.         0.         0.        ]]
10

上题np.random.choice参数如下:

Generates a random sample from a given 1-D array

Parameters
----------
a : 1-D array-like or int
    If an ndarray, a random sample is generated from its elements.
    If an int, the random sample is generated as if a were np.arange(a)
size : int or tuple of ints, optional
    Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
    ``m * n * k`` samples are drawn.  Default is None, in which case a
    single value is returned.
replace : boolean, optional
    Whether the sample is with or without replacement
p : 1-D array-like, optional
    The probabilities associated with each entry in a.
    If not given the sample assumes a uniform distribution over all
    entries in a.

Returns
-------
samples : single item or ndarray
    The generated random samples

ndarray 的索引

ndarray 的简单索引:

a = np.random.random(7,6)
print(a[1])  # 矩阵第二行

print(a[1][-1])
print(a[1, -1])  # 矩阵第二行倒数第一列的数据,以上两种方式均可;但是第一种方法
				 # 实际上耗时高于第二种,因为它是先创建一个临时索引组 a[1] ,然
				 # 后在其中索引倒数第一个值,而非直接索引
				 
print(a[1,:])  # 矩阵第二行,输出仍为 numpy.ndarray
print(a[:,1])  # 矩阵第二列,输出仍为 numpy.ndarray,是行向量而非(4,1)的数组

print(a[1:3,1]) # 矩阵第二列第二至三行的数据;在 x:y 中不包含 y;不填写x/y默认
					 # 索引到首/尾,y 可以超过最大行/列索引,但只会输出到末尾值
print(a[:,1:3]) # 矩阵第二至第三列的所有行

print(a[::2,:]) # 矩阵奇数行,切片格式为 start:stop:step,与元组完全相同
print(a[1:6:2]) # 矩阵第二到第六行,间隔为2(第二、四、六行,总共三行)

print(a[np.array([[1,1],[2,3]])]) # 也可以利用 narray 来进行索引

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

# 可以直接应用 Python 的切片进行行向量的颠倒(而非转置)
# list[start:stop:step], step 为负则从后向前索引,list
# 为列表、字符串或者是这里的 numpy.ndarray 等
print(np.arange(5))
print(np.arange(5)[::-1])

# 也可以对数组进行这种操作,但最终仅是列向量的颠倒
a = np.arange(15).reshape((5, 3)) 
print(a,'\n\n',a[::-1])

#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

a = np.ones((6,6))
a[1:-1,1:-1] = 0
print(a)

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

# 有关奇偶位置切片的问题
a = np.zeros((8, 8))
a[::2, ::2] = 1
a[1::2, 1::2] = 1
print(a)

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

print(np.unravel_index(100, (6, 7, 8)))

np.unravel_index 是一个获取某种矩阵特定位置/顺序的索引的函数,非常方便(尤其对于(x1,x2,x3,…)这种变态 shape)。有关 np.unravel_index 的讲解可以查看这篇博客(https://blog.youkuaiyun.com/kai123wen/article/details/98851946)

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

a = np.random.randint(0, 9, 10)
a[(a >= 3) & (a <= 8)] *= -1
print(a)

这里使用到了布尔索引(有空再研究)

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

a = np.random.uniform(0,10,10)
a[a.argmax()] = 0

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

#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
(枚举法给出数组的等价形式?

a = np.arange(24).reshape((2,3,4))
for index, x in np.ndenumerate(a):
    print(index,x)						# index 的类型为 tuple

ndarray 的基本属性&运算

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

a1 = np.empty((3, 2), np.uint32)
a2 = np.empty((3, 2), np.float64)
print(a1.itemsize * a1.size)
print(a2.itemsize * a2.size)

ndarray对象属性:

指令功能
ndarray.ndim数组的秩
ndarray.shape数组的维度
ndarray.size数组的元素总个数(大小)
ndarray.dtype数组中元素类型
ndarray.itemsize数组中每个元素的字节大小

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

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

# np.nonzero 的功能如下
>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
       [0, 4, 0],
       [5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))

>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
       [1, 1],
       [2, 0],
       [2, 1]])

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

a = np.random.random((10,10))
print(a.max(),a.min()) # 也可以使用 np.max(a)

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

a1 = np.random.random((4,5))
a2 = np.pad(a, 1, pad_with, padder=0)
print(a2)
# np.pad 还有其他用法,可以自己用 np.info 查看一下(其实是我懒得看了,以后再更)
# 这个题也可以复杂一些:
a1 = np.zeros((2,3))
a2 = np.ones(tuple(map(sum,zip(a1.shape,(2,2))))) # 因为元组中各个元素不能直接相加
									# 如(3,4)+(1,1)所得为(3,4,1,1),因此只能用这样
									# 一个复杂的步骤
a2[1:-1,1:-1] = a1 # 类似于第15题
print(a2)

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

# 这个题自己 print 就行
0 * np.nan				   # nan
np.nan == np.nan		   # False
np.inf > np.nan			   # False
np.nan - np.nan			   # nan
np.nan in set([np.nan])    # True
0.3 == 3 * 0.1			   # False
						   # 浮点数可以比大小但是不能判断相等
						   # 需要其他方法进行相等判断

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

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


# np.diag 的一些解释

Extract a diagonal or construct a diagonal array.

See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.

Parameters
----------
v : array_like
    If `v` is a 2-D array, return a copy of its `k`-th diagonal.
    If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
    diagonal. # 这一条既是本题解决方法
k : int, optional
    Diagonal in question. The default is 0. Use `k>0` for diagonals
    above the main diagonal, and `k<0` for diagonals below the main
    diagonal.

Returns
-------
out : ndarray
    The extracted diagonal or constructed diagonal array.

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

Z**Z			# legal,结果为Z^(Z),对每个元素broad
2 << Z >> 2		# legal,但是不太清楚是啥运算
Z <- Z			# legal,但print出来是对Z < -Z的判断,看来和空格位置无关(长的像R的赋值一样)
1j*Z			# legal,复数运算
Z/1/1			# legal
Z<Z>Z			# illegal,也不清楚这是要干啥

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

np.array(0) / np.array(0)	# nan,但是会warning,除法运算(float)
np.array(0) // np.array(0)	# 0,同样会warning,除法运算(int)
np.array([np.nan]).astype(int).astype(float)	# [-2.14748365e+09]

#### 29. How to round away from zero a float array ? (★☆☆)
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)

取整问题

a =np.random.uniform(-10, 10, 10)
print(a)
print(np.round(a))	# 四舍五入, 但是0.5奇进偶不进
print(np.ceil(a))	# 天花板函数,向上取整
print(np.floor(a))	# 地板函数,向下取整
print(np.rint(a))	# 四舍五入
print(np.trunc(a))	# 截断,保留整数部分
print(np.modf(a))	# 把整数和小数分开,返回一个元组,第一个元素为
					# 小数部分的narray,第二个为整数部分的narray
print(a.astype(int)) # 截断,保留整数部分
print(a-a%1)		# 模1得小数部分,类似截断

print(np.floor(a[a > 0]))  # 36题答案,按照正数的特性换用取整函数即可

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

print(np.intersect1d([1, 2, 3, 4, 5], [7, 6, 5, 4])) # 不会考虑相同元素的顺序

a1 = np.array([i for i in range(8)]).reshape((4,2))
a2 = np.array([7-i for i in range(8)]).reshape((2,4))
print(a1, '\n\n', a2, '\n\n', np.intersect1d(a1, a2)) # 也不考虑矩阵大小

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

np.sqrt(-1) == np.emath.sqrt(-1)

print(np.sqrt(-1) == np.emath.sqrt(-1)) 
False
print(np.sqrt(-1)) # 在实数域,结果是nan
print(np.emath.sqrt(-1)) # 在复数域开根,结果是1j

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

A = np.random.uniform(0,10,(2,4))
B = np.random.uniform(0,10,(2,4))
print((A+B)*(-A/2))		# 这样相当于又创建了多个临时区域来储存结果

np.add(A,B,out=B)		# out=B 就将结果覆盖了原来的B
#print(B)    此时B已经是A+B了,且直接输出给了B,没有新建区域来储存A+B
np.divide(A,2,out=A)
np.negative(A,out=A)
print(np.multiply(A, B, out=A))

有关 numpy 中的拷贝可以参考这里

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

a = np.zeros((5,2))
print(a.flags)

# array的基本属性
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True			 # 是否可以写入
  ALIGNED : True			 # 是否对齐
  WRITEBACKIFCOPY : False	 # 强拷贝后能否通过写入拷贝改写原array
  UPDATEIFCOPY : False		 # 强拷贝后能否通过更新拷贝改写原array

# 本题解答:
a.flags.writeable = False
a[0] = 1
#报错:
ValueError: assignment destination is read-only



一些较为常用的简单运算函数:

函数名简写或解释函数名简写或解释
np.add(x,y)x+y (broad)np.mod(x,y)取模
np.subtract(x,y)x-ynp.power(x,y)x**y(broad的元素乘方)
np.multiply(x,y)x*y(broad的元素相乘)np.dot(x,y)x@y(XYT)
np.cross(x,y)向量叉乘(broad的行向量叉乘)np.outer(x,y)XTY
a.conj()a 的共轭a.transpose()a.T(a 的转置)
np.divide(x,y)x/y (broad)np.sqrt(x)√x (broad)

其中有关乘法运算给出几个例子:

# example 1
a1 = np.array([1,0,0])
a2 = np.array([0,1,0])
print(np.multiply(a1,a2),' ',np.dot(a1,a2),' ',np.cross(a1,a2),'\n\n',np.outer(a1,a2))
# example 2
a3 = np.array([[1,0,0],[0,1,0]])
a4 = np.array([[0,1,0],[1,0,0]])
print(np.multiply(a3,a4),'\n\n',np.cross(a3,a4))
# 输出结果如下
[0 0 0]   0   [0 0 1] 

 [[0 1 0]
 [0 0 0]
 [0 0 0]] 

[[0 0 0]
 [0 0 0]] 

 [[ 0  0  1]
 [ 0  0 -1]]

以下是关于np.add()的一些说明,其他简单运算函数的参数大体相同:

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.
    If ``x1.shape != x2.shape``, they must be broadcastable to a common
    shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or None,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``, locations within it where the condition is False will
    remain uninitialized.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.
    This is a scalar if both `x1` and `x2` are scalars.

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

a = np.random.random(30)
print(a.mean())
# 更快一点
print(np.mean(np.random.random(30)))

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

不太清楚他这里的 Normalize 是想怎么处理,看了看别人的也五花八门,就随便写了几个:array.std()计算数组方差,a.mean()计算数组平均数(均是对数组内所有元素进行统计,而不是分行或者分列)

a = np.random.random((6,5))
print(a / np.sqrt(a.size * (np.power(a.mean(),2) + np.power(a.std(),2)))) # 除以几何平均值
print((a - a.mean()) / a.std())  # 高斯分布的归一化

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

a1 = np.full((5,3),1)
a2 = np.full((3,2),2)
print(a1 @ a2)
print(np.dot(a1, a2))

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

# Author: Jake VanderPlas

print(sum(range(5),-1))  # 9 = 0+1+2+3+4+(-1)
from numpy import *
print(sum(range(5),-1))  # 10

这道题实际上是指出了Python内置sum()函数和np.sum()的区别

sum(iterable[, start]) # Python内置,iterable为可迭代对象,如:列表、元组、集合;
					   # start为前者总和后再加上的参数值
np.sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)
					   # 题目中所输入的-1等价于 axis=-1,一维数组就是 axis=0,所以
					   # 上题就是直接按行求和;对于二维数组和 axis=1 相同(倒数第一
					   # 个),那就是按列求和,最终输出一个行向量

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

import time

a = np.arange(20)

start1 = time.perf_counter()
print(a.sum())
end1 = time.perf_counter()
print('Running time: %s Seconds'%(end1-start1))

start2 = time.perf_counter()
print(np.add.reduce(a))
end2 = time.perf_counter()
print('Running time: %s Seconds'%(end2-start2))

# 结果
190
Running time: 3.469999999999862e-05 Seconds
190
Running time: 9.700000000001374e-06 Seconds

np.sum()和np.add.reduce()在功能上没有任何区别。但是这种方法仅适用于行向量,因为np.sum()默认是求所有元素之和,而np.add.reduce()和np.add()一样由 axis=0 的默认设置,所以对于矩阵或数组来说需要进一步设置一下。如下:

import time
a = np.arange(20).reshape((4,5))
print(a.sum())
print(np.sum(a, axis=0))
print(np.add.reduce(a,axis=(0,1)))
print(np.add.reduce(a))

#结果
190
[30 34 38 42 46]
190
[30 34 38 42 46]

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

a1 = np.random.uniform(0,10,5)
a2 = np.random.uniform(0,10,5)
print(a1 == a2)					 # 判断每个对应位置的元素是否相同,输出为 ndarray
print(np.allclose(a1,a2))		 # Returns True if two arrays are element-wise equal within a tolerance.
print(np.array_equal(a1,a2))	 # True if two arrays have the same shape and elements, False otherwise.
								 # 后两种方法均是返回单个布尔值

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

a = np.random.uniform(-10,10,(10,2))
#1  np.column_stack可以按列合并矩阵或向量;该法实际上是有一定问题的,后说
a_polar = np.column_stack((np.sqrt(np.add.reduce(np.square(a), axis=1)), np.arctan(np.divide.reduce(a, axis=1))))
#2  也可以先创建一个和原矩阵相同大小的储区
a_polar = np.zeros_like(a)
a_polar[:,0] = np.sqrt(np.square(a[:,0]) + np.square(a[:,1]))
a_polar[:,1] = np.arctan2(a[:,1],a[:,0])

需要注意的是np.arctan仅接受单个数组作为正弦值输入,返回范围在[−π/2, π/2];而np.arctan2接受两个数组(或向量)作为输入(前者作为分子或对边,后者作为分母或邻边),当然他们必须是可以 broad 的,并且最终返回值的范围是 [−π, π],因为你可以根据两个值判断象限。所以上题中第一种方法用np.arctan(np.divide.reduce(a, axis=1))是不正确的,因为极坐标θ显然是 (−π, π] 的,还是得换成np.arctan2(a[:,1],a[:,0])。

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

X = np.arange(6,10)
Y = np.arange(1,5)
# 1 暴力解题
xx, yy = np.size(X),np.size(Y)
C = np.zeros((xx,yy))
for i in range(xx):
    for j in range(yy):
        C[i,j] = 1/(X[i]-Y[j])
print(C,'\n')
# 2 numpy的人性化方法
C = 1.0 / np.subtract.outer(X, Y)
print(C)
# 结果,两个一样(显示是这样的)
[[0.2        0.25       0.33333333 0.5       ]
 [0.16666667 0.2        0.25       0.33333333]
 [0.14285714 0.16666667 0.2        0.25      ]
 [0.125      0.14285714 0.16666667 0.2       ]]

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

a = np.random.random((100,2))
X,Y = np.atleast_2d(a[:,0], a[:,1])
Dist = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(Dist)

# 需要注意的是单纯将X赋为a的第一列索引,所得为行向量
X2 = a[:,0]
print(X2)
# 而使用np.atleast_2d可以确保赋值所得至少为二维矩阵
print(X)

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

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

a = np.random.uniform(-10,10,(4,5))
# print(np.mean(a,axis=1,keepdims=True))
a = np.subtract(a,np.mean(a,axis=1,keepdims=True))
print(a)

数据类型

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

有关numpy的数据类型(dtype)可以参考这里

print(np.dtype([('R', np.int32), ('G', np.int32), ('B', np.int32), ('A', np.int32)]))

numpy.datetime64是 numpy 用来储存日期的类型,你可以把他看成按年-月-日进制的数据(逢30/31日进1月哈哈哈)

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

today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(type(today),today,tomorrow)

<class 'numpy.datetime64'> 2022-11-09 2022-11-10 # 结果如左

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

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

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

a = np.empty((5,2),dtype=np.float32)
print(np.dtype(a[0,0]))
a = a.astype(np.int32,copy=False)
print(np.dtype(a[0,0]))

np.astype用于更改数组内元素类型,但仅在赋值语句中能发挥真正作用(单纯键入a.astype(np.int32,copy=False)没有任何实际效应)

Python NumPy 的学习笔记 阅读详情

相关推荐

Python学习笔记:初探NumPy世界

文章目录一、NumPy概述二、多维数组对象三、创建NumPy多维数组1、利用array()函数创建NumPy数组2、创建NumPy数组的其它函数(1)利用zeros函数创建元素全为0的数组(2)利用ones函数创建元素全为1的数组(3)利用empty函数创建数组(4)arange函数是Python内置函数range的数组值版本3、创建数组函数表4、数组元素的数据类型四、NumPy数组的运算1、数组与数组的算术运算2、数组与标量的算术运算3、数组与数组的关系运算4、数组与标量的关系运算5、广播概述五、基本索引

howard2005的专栏 1116

numpy-100(附答案、详细注释和知识点拓展)

Numpy-100(numpy100道练习题)原项目地址:https://github.com/rougier/numpy-100 本文在numpy-100原项目(带solution版)地基础上,将部分练习的答案替换为了更常见、更易想的解法,并为原项目中每一题的解答添加了较详细的注释以及部分相应知识点的介绍和扩展。 (未完成版) #1、Import the numpy package under ...

zx的博客 5470

python numpy 反转 reverse示例

python 的向量反转有一个很简单的办法 # 创建向量 impot numpy as np a = np.array([1,2,3,4,5,6]) b=a[::-1] print(b) 结果: [6, 5, 4, 3, 2, 1] 或者 可以使用 flipud function # 创建向量 impot numpy as np a = np.array([1,2,3,4,5,6]) b== np.flipud(ini_array) print(b) 结果也是 [6, 5, 4, 3, 2, 1] 以上这篇python numpy 反转 reverse示例就是小编分享给大家的全部内容了,希

50道numpy练习题

这是在stackoverflow和numpy文档里汇总的numpy练习题,目的是为新老用户提供快速参考。1. Import the numpy package under...

Python与数据分析 7287

免安装版Notepad++终极配置:右键菜单+图标美化+多文件批量处理(2024新版)

本文详细介绍了如何为免安装版Notepad++进行终极配置,包括右键菜单添加、图标美化以及多文件批量处理功能。通过注册表编辑和高级定制,用户可以在便携版中实现与安装版相同的功能体验,同时保持系统整洁。特别适合开发者、系统管理员和效率追求者使用。

nut55的博客 830

RC模型车多电机驱动方案:从电调PWM原理到四电机安全连接实战

在电机控制领域,PWM(脉冲宽度调制)是实现精确调速的核心技术。其原理是通过调节固定周期内高电平的脉宽来编码控制指令,进而驱动电子调速器(电调)改变输出功率。这项技术对于需要多电机协同工作的场景,如RC模型车的差速转向或重型负载驱动,具有关键价值。它能实现动力的精细分配与同步,提升车辆的可控性与通过性。在实际应用中,为确保系统稳定,必须关注电流分配与信号同步问题。例如,通过为每个电机配备独立电调并采用信号并联(Y线)的方式,可以构建可靠的四电机驱动系统。这种方案能有效避免因单个电调过载或电机反电动势不一致导

weixin_30664615的博客 381

100 numpy exercises

题目 题目地址:https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises.md Import the numpy package under the name np (★☆☆) Print the numpy version and the configuration (★☆☆) Create a null vector of size 10 (★☆☆) How to find the memory size of any a

我是菜鸡 2838

DBeaver连接ClickHouse保姆级教程:从安装到成功测试(附驱动下载问题解决)

本文提供了一份详细的DBeaver连接ClickHouse实战指南,重点解决了驱动下载失败等常见问题。文章从环境准备、DBeaver安装讲起,详细阐述了手动配置ClickHouse驱动的可靠方案,并逐步指导完成连接配置与测试,最后介绍了基础操作与查询优化技巧,旨在帮助用户高效完成连接并快速上手使用。

pink的博客 879

function函数的用法python_Python numpy.fromfunction函数方法的使用

numpy.fromfunctionnumpy.fromfunction(function,shape,*,dtype=,**kwargs) [source]通过在每个坐标上执行一个函数来构造一个数组。因此,结果数组在坐标(x, y, z)处有一个值fn(x, y, z)。参数:function:callable该函数使用N个参数调用,其中N是的秩shape。每个参数代表沿特...

weixin_39639049的博客 955

S7-1200PLC 2轴直线插补详细算法(完整源代码)

速度轴V90PN总线伺服梯形加减速速度控制(标准报文1应用)_v90伺服加减速时间怎么调整-优快云博客文章浏览阅读288次。

RXXW_Dor的博客 4256

MyBatis-Plus 实战:敏感字段自动加解密支持模糊查询

本文基于MyBatis-Plus框架提出了一种全链路敏感字段加密方案。通过自定义TypeHandler实现数据入库自动加密和查询自动解密,结合重写LambdaQueryWrapper处理查询条件加密,并适配多种查询方式。方案核心包括:1)AESUtil工具类提供加解密基础能力;2)EncryptTypeHandler实现字段类型转换;3)实体类通过注解配置加密字段。该方案在保证数据安全的同时,对业务代码侵入性小,支持姓名、手机号等敏感信息的全流程加密处理,满足系统开发的安全需求。

蔡定努 596

Numpy 100 exercise 笔记

Numpy 100 / PyCharm 学习笔记Intro1. Import the numpy package under the name np2. Print the numpy version and the configuration3. Create a null vector of size 104. How to find the memory size of any array47.48.49.50. How to find the closest value (to a given sc

zhaotian151的博客 4450

DeepSeek赋能公文写作:从高效成文到精准传情的全维度指南

摘要:AI赋能公文写作的精准化实践 公文写作长期面临框架混乱、素材匮乏、表达不规范、修改低效等痛点。DeepSeek等AI工具通过"精准指令+分步赋能"模式实现突破:首先明确公文的目的性、逻辑性和规范性特征;其次采用包含场景、类型、目的等要素的指令模板;再分四步实施:框架搭建确保层次分明,内容填充解决素材问题,表达优化适配不同语体,合规校验把关格式规范。典型案例显示,AI能将数据罗列转化为"数据+成果+价值"的生动表述,使公文既规范又具感染力。这种AI赋能的写作方法显

通俗易懂学IT 231

Python学习笔记 | Numpy库全部

Python学习笔记|turtle库画图案例简述涉及知识点python代码总结 案例简述 画出不同size的五角星 涉及知识点 turtle库 python代码 import turtle def draw_pentagram(size): """ 绘制五角星 """ count = 1 while count <= 5: turtl...

weixin_44878159的博客 790

Windows Docker Desktop部署MaxKB详细教程

MaxKB(Max Knowledge Base)是一款基于大语言模型(LLM)和检索增强生成(RAG)技术的开源知识库问答系统,旨在帮助企业、教育机构及研究组织高效管理知识并提供智能问答服务。

猿小白的博客 1372

使用 Fargate 在 AWS ECS 上运行 Spring Boot 应用程序

本文介绍了使用AWS Fargate支持的ECS部署SpringBoot应用的完整流程。主要内容包括:1)将SpringBoot应用打包为Docker镜像并推送至ECR;2)创建任务定义配置CPU、内存和网络等参数;3)设置ECS服务管理任务运行;4)配置负载均衡器分配流量;5)设计VPC网络和安全组规则确保安全访问;6)使用SSM参数存储管理敏感信息。整个过程实现了无服务器化部署,既保持了应用控制权,又免除了基础设施管理负担,是扩展Web服务的可靠方案。

介绍AWS Azure GCP devops Terraform 等技术 512

Python学习笔记合集(Numpy总结)

Python学习笔记Numpy合集(总结)零基础学Numpy,就来这里看Numpy学习笔记,简单易懂!

qq_54129105的博客 4224

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

python第三方库numpy学习笔记

​numpy是一款功能强大的Python库,专注于科学计算和数据处理。它底层使用C语言实现,按照类型存储数据,因此比Python列表更高效。numpy提供了简洁易读的语法和强大的函数库,用于操作数组、矩阵乘法、傅里叶变换等等。此外,numpy也提供了大量的线性代数和随机数生成函数,方便进行向量和矩阵运算,同时也可以生成服从不同分布的随机数。总之,numpy在科学计算和数据处理中是一个非常重要的工具,为用户提供了高效的数据存储方式和快捷的数据处理方法。

qy85329140的博客 339

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Python 商务数据分析—— NumPy 学习笔记Ⅱ

本文系统介绍了NumPy数组的核心操作技术,主要包含六大模块内容:1)数组索引与切片(四种索引方式及示例);2)元素操作(替换与条件处理);3)广播机制(原则与兼容性判断);4)形状操作(叠加/切割/转置);5)Axis轴概念解析(本质与运算示例);6)销售数据综合实战(三维数据聚合计算)。全文通过代码示例详细演示了每种操作的具体实现,重点解析了广播规则、轴方向运算等难点,最后通过销售数据案例展示了多维数组的实际应用。掌握这些核心操作可有效提升数组数据处理效率。

2302_79239614的博客 627

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Python高级学习笔记-day01-Numpy库

初学小小白,个人笔记使用,仅供参考

XZSSWJS的博客 881

python之numpy学习笔记

PYTHON numpy通用计算函数 通用函数,就是能同时对元素内所有元素逐个进行运算的函数,例如[1,2,3,4]4,可以每个元素都4; 虽然用for循环也可以做到同样的效果,使用numpy则会更快; numpy,scipy.special; 符号:+、-、-、*、/、//、**、%、absolute(abs)均为通用计算符号,三角函数(sin, cos, tan)与反三角函数也可(arcsi...

coolljp21的博客 347

Python中NumPy模块(Python for Data Analysis学习笔记)

文章目录numpy-数组numpy-矩阵 numpy-数组 numpy中的array运算更快 import numpy as np my_arr = np.arange(1000000) my_list = list(range(1000000)) #%time是ipython的特殊功能 %time for _ in range(10): my_arr2 = my_arr * 2 %time...

Grace_lili博客 523

【学习笔记】python数据分析-Numpy

ndarray多维数组 通常来说,ndarry是一个通用的同构数据容器(即其中的所有元素都需要是相同的类型)。创建好一个ndarray数组时,同时会在内存中存储ndarray的shape和dtype。shape是ndarray维度大小的元组,dtype是解释说明ndarray数据类型的对象。 创建一个 ndarray 只需调用 NumPy 的 array 函数即可: import numpy as np data1= [[5, 2, 3, 4, 9], [5, 7, 9, 20, 18]] arr1= n

qq_39951637的博客 770

python学习笔记之Numpy

此文为笔者学习过程中对Numpy的笔记,其中主要为笔者对Numpy新鲜知识点的记录。注意此文不适合初学者,仅作为笔者日后查漏补缺使用,初学者还是找些系统介绍文章来学习。

何小智的博客 217

python学习笔记之numpy库的使用——超详细

文章目录NumPy介绍一.如何创建1.导入Numpy库,并命名为np:2.查看版本3.通过列表创建一维数组:4.通过列表创建二维数组:5.创建全为0的二维数组6.创建全为1的三维数组7.创建一维等差数组8. 创建二维等差数组:9. 创建单位矩阵(二维数组):10. 创建二维随机数组:11.创建二维随机整数数组(数值小于 5):二.数组运算12.一维数组加法运算:13.一维数组减法运算:14. 一维数组乘法运算:15.一维数组除法运算:16.二维数组的运算,相应位置上进行+-*/17 矩阵乘法运算(注意与上题

逐梦er的博客 8万+

Python学习笔记——NumPy

①概念向量数据是指存储一系列同类数据的有序数据结构。②分类python中的列表和元组可以用来存储向量数据。分为 一维列表,二维列表,三(多)维列表。③向量数据结构的理解。

小橙子的博客 614
上一篇: matplotlib制作雷达图报错ValueError及连线不完整问题解决
下一篇: GROMACS的安装以及部分常见报错
CocoCream
博客等级 码龄6年 195粉丝 14原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值