• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python中numpy多维数组的用法

python 搞java代码 3年前 (2022-05-21) 40次浏览 已收录 0个评论

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

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


<p style="line-height: 1.75em"><span>a = <a href="https://www.gaodaima.com/tag/np" title="查看更多关于np的文章" target="_blank">np</a>.arange(4)

输出:

<a href="https://www.gaodaima.com/tag/array" title="查看更多关于array的文章" target="_blank">array</a>([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]])<br></span></p>

www#gaodaima.com来源gao@daima#com搞(%代@#码网搞代码

多维数组操作过程中的类型转换

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


<p style="line-height: 1.75em"><span>a = np.ones((2,3),dtype=int)  # int32

b = np.random.random((2,3))  # float64

b += a # 正确 

a += b # 错误<br></span></p>
<p style="line-height: 1.75em"><span>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'<br></span></p>


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


<p style="line-height: 1.75em"><span>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)<br></span></p>


其他的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多维数组的用法。更多Python学习推荐:云海天Python教程网

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python中numpy多维数组的用法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址