python中array的用法_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]])

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

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 # 错误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'

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

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)

其他的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学习推荐:JQ教程网Python大全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值