Python科学计算库之numpy

numpy

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

ndarray的特点

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

- 一种由相同类型的元素组成的多维数组,元素数量是事先给定好的
- 元素的数据类型由dtype(data-type)对象来指定,每个ndarray只有一种dtype类型
- ndarray的大小固定,创建好数组后数组大小是不会再发生改变

ndarray的创建

  • array函数:接收一个普通的python序列,并将其转换为ndarray

    b = np.array([
        [1,2,3],
        [4,5,6]
    
    ])
    print(b)
    
    out:
    [[1 2 3]
     [4 5 6]]
    
  • zeros函数:创建指定长度或者形状的全零数组。

    d = np.zeros((2,3))
    print(d)
    
    out:
    [[ 0.  0.  0.]
     [ 0.  0.  0.]]
    
  • ones函数:创建指定长度或者形状的全1数组。

    e = np.ones((3,4))
    print(e)
    
    out:
    [[ 1.  1.  1.  1.]
     [ 1.  1.  1.  1.]
     [ 1.  1.  1.  1.]]
    
  • empty函数:创建一个没有任何具体值的数组(准备地说是创建一些未初始化的ndarray多维数组)

    f = np.empty((6,6))
    print(f)
    

ndarray创建基本数据类型


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其它创建方式

  • arange函数: 类似python的range函数,通过指定开始值终值步长来创建一个一维数组(不包含终值)。

    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]
    
  • linspace函数:通过指定开始值终值元素个数来创建一个一维数组,数组的数据元素符合等差数列,可以通过endpoint关键字指定是否包含终值,默认包含终值

    i = np.linspace(0,25,6,endpoint = True)
    print(i)  #输出:[  0.   5.  10.  15.  20.  25.]
    
  • logspace函数:和linspace函数类似,不过创建的是等比数列数组

    j = np.logspace(2,3,5)
    print(j) # 输出:[  100. 177.827941  316.22776602  562.34132519  1000.  ]
    
  • random函数:使用随机数填充数组,使用numpy.random中的random()函数来创建随机元素,数组包含的元素数量由参数决定

    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的属性

  • dtype:用于说明数组元素数据类型的对象
  • astype:用于对数组元素数据类型进行转换
  • shape:数组的各个维度大小的元组,即数组的形状
  • size:元素总个数,即shape中各个数的相乘
  • ndim:数组的维度数量

    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数组对象而言,可以通过调用修改形状的方法从而改变数组的结构形状。

- 直接修改数组ndarray的shape值, 要求修改后乘积不变。
- 直接使用reshape函数创建一个改变尺寸的新数组,原数组的shape保持不变,但是新数组和原数组共享一个内存空间,修改数组中的值都会对另外一个产生影响,另外要求新数组的元素个数和原数组一致。
- 当指定某一个轴为-1的时候,表示将根据数组元素的数量自动计算该轴的长度值。

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数组的切片同Python中的切片

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数组与标量、数组之间的运算

  • 数组不用循环即可对每个元素执行批量的算术运算操作,这个过程叫做矢量化,即用数组表达式代替循环的做法。矢量化数组运算性能比纯Python方式快上一两个数据级。

  • 大小相等的两个数组之间的任何算术运算都会将其运算应用到元素级上的操作,在NumPy中,大小相等的数组之间的运算,为元素级运算,即只用于位置相同的元素之间,所得的运算结果组成一个新的数组,运算结果的位置跟操作数位置相同。

ndarray数组的矩阵积

矩阵:多维数组即矩阵
矩阵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数组转置与轴对换

  • 数组转置是指将shape进行重置操作,并将其值重置为原始shape元组的倒置,比如原始的shape值为:(2,3,4),那么转置后的新元组的shape的值为: (4,3,2)
  • 对于二维数组而言(矩阵)数组的转置其实就是矩阵的转置可以通过调用数组的transpose函数或者T属性进行数组转置操作

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)

常用函数

常用一元函数

常用二元函数

 聚合函数

聚合函数是对一组值(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的区别

  • numpy.random.random(name,A)

    这个可以改你要的随机数是什么分布,可以调整随机数的参数,例如正态分布可以改两个参数
    
  • numpy.random.randn(d0, d1, …, dn)

    从标准正态分布中返回一个或多个样本值。 
    
  • numpy.random.rand(d0, d1, …, dn)

    均匀分布随机样本位于[0, 1)中。
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值