numpy基本操作

numpy提供了一种n维数组对象:np.array()。

将数组封装为对象,有助于科学计算中的诸多操作。

下面给出示例


import numpy as np

#创建ndarray数组,一维数组,二维数组,利用reshape调整数组的行和列。

a=np.array([1,2,3])

print(a)

b=np.array([[1,2,3],[4,5,6]])

print('b is ',end="")

print(b)

a2=b.reshape(3,2)

print("a is",end="")

print(a2)

#输出结果
[1 2 3]
b is [[1 2 3]
 [4 5 6]]
a is[[1 2]
 [3 4]
 [5 6]]
#切片和索引
a3=np.arange(15)
print("a3 is %s" % a3)
#利用内置的slice函数来构造一个slice对象。
#slice函数的三个参数为,起点,终点
b3=slice(3,14,2)
print("b3 is %s"%a3[b3])
#输出结果
a3 is [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
b3 is [ 3  5  7  9 11 13]
#还可以用冒号来直接对ndarray对象切片
a4=np.arange(17)
b4=a4[3:16:3] #三个参数都是可缺省的。
print(b4)

[ 3  6  9 12 15]
#tensor
def myfunc(a,b):
    if a>b:
        return a*b
    else:
        return a+b
vfunc=np.vectorize(myfunc)
print(vfunc([23,2,3,1,2,3,4],[43,21,8,92,3,2,1]))
print(vfunc([[1,2,3],[4,5,6]],[[7,8,9],[6,3,1]]))

[66 23 11 93  5  6  4]
[[ 8 10 12]
 [10 15  6]]
#多项式函数
p=np.poly1d([2,3,4,5,3])
print(np.poly1d(p))
#结果第一行表现第二行中x的次方。

   4     3     2
2 x + 3 x + 4 x + 5 x + 3

你可能感兴趣的:(numpy基本操作)