Python中numpy多维数组的用法

361次阅读
没有评论

Python中numpy多维数组的用法

继上篇讲过numpy如何构建多维数组之后,今天我们来学习numpy多维数组的用法。

加法和减法操作要求操作双方的维数信息一致,均为M*N为数组方可正确执行操作。

a = np.arange(4) 输出: array([0, 1, 2, 3]) b = a**2 输出: array([0, 1, 4, 9]) c = 10*np.sin(a) 输出: array([ 0.  , 8.41470985, 9.09297427, 1.41120008]) n < 35 输出: array([ True, True, True, True], dtype=bool) A = np.array([[1,1],[0,1]]) B = np.array([[2,0],[3,4]]) C = A * B # 元素点乘 输出: array([[2, 0],  [0, 4]]) D = A.dot(B) # 矩阵乘法 输出: array([[5, 4],  [3, 4]]) E = np.dot(A,B) # 矩阵乘法 输出: array([[5, 4],  [3, 4]])

</pre>
多维数组操作过程中的类型转换

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting)

 

即操作不同类型的多维数组时,结果自动转换为精度更高类型的数组,即upcasting

 

a = np.ones((2,3),dtype=int)  # int32 b = np.random.random((2,3))  # float64 b += a # 正确 a += b # 错误
<pre class="brush:js;toolbar:false">

a = np.ones(3,dtype=np.int32) b = np.linspace(0,pi,3) c = a + b d = np.exp(c*1j) 输出: array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,  -0.54030231-0.84147098j]) d.dtype.name 输出: ‘complex128’

</pre>
 

多维数组的一元操作,如求和、求最小值、最大值等

 

a = np.random.random((2,3)) a.sum() a.min() a.max() b = np.arange(12).reshape(3,4) 输出: array([[ 0, 1, 2, 3],  [ 4, 5, 6, 7],  [ 8, 9, 10, 11]]) b.sum(axis=0) # 按列求和 输出: array([12, 15, 18, 21]) b.sum(axis=1) # 按行求和 输出: array([ 6, 22, 38]) b.cumsum(axis=0) # 按列进行元素累加 输出: array([[ 0, 1, 2, 3],  [ 4, 6, 8, 10],  [12, 15, 18, 21]]) b.cumsum(axis=1) # 按行进行元素累加 输出: array([[ 0, 1, 3, 6],  [ 4, 9, 15, 22],  [ 8, 17, 27, 38]]) universal functions B = np.arange(3) np.exp(B) np.sqrt(B) C = np.array([2.,-1.,4.]) np.add(B,C)
<pre class="brush:js;toolbar:false">

 

其他的ufunc函数包括:

all, any, apply_along_axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor,inner, lexsort, max, maximum, mean, median, min, minimum, nonzero, outer, prod, re, round, sort, std, sum, trace, transpose, var,vdot, vectorize, where

以上就是Python中numpy多维数组的用法。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-07发表,共计1607字。
新手QQ群:570568346,欢迎进群讨论 Python51学习