科学计算库numpy基础

2020-10-09  本文已影响0人  程序媛啊

numpy

numpy的核心数据结构是ndarray,可以创建N维数组

ndarray的特点

ndarray(N-dimensional array):N维数组

ndarray的创建

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

    out:
    [[1 2 3]
     [4 5 6]]
    d = np.zeros((2,3))
    print(d)
    
    out:
    [[ 0.  0.  0.]
     [ 0.  0.  0.]]
    e = np.ones((3,4))
    print(e)
    
    out:
    [[ 1.  1.  1.  1.]
     [ 1.  1.  1.  1.]
     [ 1.  1.  1.  1.]]
    f = np.empty((6,6))
    print(f)

ndarray创建基本数据类型

image.png image.png

code:

import numpy as np
a1 = np.array(["Python","Java","C++","PHP"])
print(a1)
a1

out:

['Python' 'Java' 'C++' 'PHP']
Out[81]:
array(['Python', 'Java', 'C++', 'PHP'], dtype='<U6')

code:

a2 = np.array(["哈哈","嘿嘿","呼呼","嘎嘎"])
print(a2)
a2

out:

[b'Python' b'Java' b'C++' b'PHP']
Out[83]:
array([b'Python', b'Java', b'C++', b'PHP'], dtype='|S8')

ndarray其它创建方式

    g = np.arange(10,50,5)
    print(g) #输出:[10 15 20 25 30 35 40 45]

    h = np.arange(30,20,-2)
    print(h) #输出: [30 28 26 24 22]
    i = np.linspace(0,25,6,endpoint = True)
    print(i)  #输出:[  0.   5.  10.  15.  20.  25.]
    j = np.logspace(2,3,5)
    print(j) # 输出:[  100. 177.827941  316.22776602  562.34132519  1000.  ]
    j = np.random.random((2,3,4))
    print(j)
    
    输出:
    [[[ 0.67133713  0.80188756  0.06388015  0.81575917]
      [ 0.21830916  0.90382401  0.0095      0.95252789]
      [ 0.54048634  0.07984948  0.9527077   0.85444074]]
    
     [[ 0.15047247  0.14771948  0.425606    0.02572186]
      [ 0.71512809  0.81017573  0.80882504  0.87543752]
      [ 0.75518265  0.73766281  0.93846421  0.31309056]]]

ndarray的属性

    c= np.array([
        [
            [1,4,7],[2,5,8]
        ],
        [
            [3,6,9],[6,6,6]
        ]
    ])
    
    print(c)
    
    输出:
    [[[1 4 7]
      [2 5 8]]
    
     [[3 6 9]
      [6 6 6]]]
    
    print(c.ndim)  # 数组的纬度数为:3
    print(c.dtype) # 数组元素数据类型为:int32
    print(c.shape) # 数组各个纬度的大小:(2, 2, 3)
    print(c.size)  #  数组的元素个数:12

    d= c.astype(float)
    print(d.dtype) #数组元素数据类型为:float64

ndarray修改数组结构

对于一个已经存在的ndarray数组对象而言,可以通过调用修改形状的方法从而改变数组的结构形状。

code:

b1 = np.arange(0,20,2)
print(b1)
print(b1.size)
print(b1.shape)

out:

[ 0  2  4  6  8 10 12 14 16 18]
10
(10,)

code:

b2 = b1.reshape(2,5)
print(b2)

out:

[[ 0  2  4  6  8]
 [10 12 14 16 18]]

code

b3 = b1.reshape(-1,2)
print(b3)
b3[2][1] = 100
print(b1)

out:

[[ 0  2]
 [ 4  6]
 [ 8 10]
 [12 14]
 [16 18]]
[  0   2   4   6   8 100  12  14  16  18]

code:

b2.shape = (1,10)
print(b2)

out:

[[  0   2   4   6   8 100  12  14  16  18]]

NumPy的基本操作

ndarray多维数组的索引

c1 =  np.array([
    [
        [5,2,4],
        [3,8,2],
    ],
    [
        [6,0,4],
        [0,1,6]
    ]

])

print(c1[1,0,2])    # out:4
print(c1[0][1][2])  # out:2

ndarray花式索引

code:

f1=np.arange(32).reshape((8,4))
print(f1)

out:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]
 [24 25 26 27]
 [28 29 30 31]]

code:

f2 = f1[[2,3,5]] #取第2,3,5行
print(f2)

out:

[[ 8  9 10 11]
 [12 13 14 15]
 [20 21 22 23]]

code:

f3 = f1[[2,3,5],[1,2,3]]  #分别取第2,3,5行中第1,2,3个元素
print(f3) #out: [ 9 14 23]

code:

f4 = f1[np.ix_([2,3,5],[1,2,3])] #分别取第2,3,5行中第1,2,3列
#f4 = f1[[2,3,5]][:,[1,2,3]]
print(f4)

out:

[[ 9 10 11]
 [13 14 15]
 [21 22 23]]

ndarray数组的切片

ndarray布尔类型索引

code:

d1 = np.arange(0,12,1)
d1.shape = (3,4)
print(d1)

out:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

code:

d2 = d1 < 6
print(d2)

out:

[[ True  True  True  True]
 [ True  True False False]
 [False False False False]]

code:

print(d1[d2])
# print(d1[d1<6])

out:

[0 1 2 3 4 5]

code:

names=np.array(['Gerry','Tom','John'])
scores=np.array([
        [98,87,76,65],
        [45,45,66,90],
        [87,76,67,91]
    ])
classs=np.array([u'语文',u'数学',u'英语',u'体育'])

e1 = names=='Gerry'
print(e1)  # [ True False False]
print(scores[e1].reshape((-1)))  #[98 87 76 65]
print(scores[(names=='Gerry')|(names=='Tom')])

out:

[[98 87 76 65]
 [45 45 66 90]]

ndarray数组与标量、数组之间的运算

ndarray数组的矩阵积

image.png

矩阵:多维数组即矩阵
矩阵C = 矩阵A*矩阵B(矩阵A的列数必须等于矩阵B的行数时,A和B才可以相乘)

code

arr1 = np.array([
    [5,2,4],
    [3,8,2],
    [6,0,4],
    [0,1,6]
])

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

arr = arr1.dot(arr2)
print(arr)

out

[[24 34]
 [20 40]
 [24 32]
 [19 15]]

ndarray数组转置与轴对换

code:

g1 = np.arange(12).reshape((3,4))
print(g1)
print(g1.shape)

out:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
(3, 4)

code:

g2 = g1.transpose()
print(g2)
print(g2.shape)

out:

[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]
(4, 3)

code:

g3 = g1.T
print(g3)
print(g3.shape)

out:

[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]
(4, 3)

常用函数

常用一元函数

image.png image.png

常用二元函数

image.png

聚合函数

聚合函数是对一组值(eg.一个数组)进行操作,返回一个单一值作为结果的函数。当然聚合函数也可以指定对某个具体的轴进行数据聚合操作;常将的聚合操作有:平均值、最大值、最小值、方差等等

i1 = np.array([
    [1,2,3,4],
    [5,6,7,8],
    [9,0,-2,-4]
])
print(i1)

print(np.max(i1))  #最大值
print(np.min(i1))  #最小值
print(np.mean(i1)) #平均值
print(np.std(i1)) # 标准差
print(np.var(i1)) #方差

print(np.max(i1,axis=1))  #axis = 1表示对行数据进行操作
print(np.mean(i1,axis=0)) #axis = 0表示对列数据进行操作
print(np.sum(i1,axis=1)) # 对行求和

where函数

where函数是三元表达式x if condition else y的矢量化版本

j1 = np.array([1.1,1.2,1.3,1.4])
j2 = np.array([2.1,2.2,0.3,2.4])
condition = j1<j2

result1 = [x if c else y for(x,y,c) in zip(j1,j2,condition)]
print(result1) # [1.1000000000000001, 1.2, 1.3, 1.3999999999999999]

print(condition)
#condition为True获取j1中的内容,为false获取j2中的内容
result2 = np.where(condition,j1,j2)
print(result2)

out:

[ 1.1  1.2  0.3  1.4]
[ True  True False  True]
[ 1.1  1.2  0.3  1.4]

unique函数

将数组中的元素进行去重操作

k1 = np.array(["a","b","c","e","b","c"])
k2 = np.unique(k1)
print(k2) #['a' 'b' 'c' 'e']

random、randn、rand的区别

    这个可以改你要的随机数是什么分布,可以调整随机数的参数,例如正态分布可以改两个参数
    从标准正态分布中返回一个或多个样本值。 
    均匀分布随机样本位于[0, 1)中。
上一篇 下一篇

猜你喜欢

热点阅读