Numpy学习笔记2

首先:

import numpy as np

1、基本排序 .sort

tang_array = np.array( [ [1.5, 1.3, 7.5 ], 
                         [5.6, 7.8, 1.2 ] ] )
np.sort(tang_array, axis = 0)
>array([[1.5,  1.3,  1.2],
        [5.6,  7.8,  7.5]])

axis可指定排序依照的

2、降序、升序组合排列:

tang_array = np.array([[1,0,6],
                       [1,7,0],
                       [2,3,1],
                       [2,4,0]])
index = np.lexsort([-1*tang_array[:,0], tang_array[:,2]])
index
>array([0, 1, 3, 2], dtype=int64)

-1表示按降序排列,【:,0】【:,2】表示所有样本,第0列和第2列。

3、数组形状 .shape

import numpy as np
tang_array = np.arange(10)
tang_array
>array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tang_array.shape
>(10,)
tang_array.shape = 2,5             #2X5的矩阵
tang_array
>array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]])

注意:构建的矩阵大小不能改变,如10个元素,构建3X4矩阵就会出错

tang_array.shape = 3,4
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-a045d1e603cc> in <module>()
----> 1 tang_array .shape = 3,4

ValueError: cannot reshape array of size 10 into shape (3,4)

4、对于一个向量,可通过.newaxis进行增加维度,变成一个矩阵。

tang_array = np.arange(10)
tang_array.shape
>(10,)
tang_array = tang_array[np.newaxis, :]      #1X10的矩阵
tang_array.shape
>(1, 10)
tang_array = np.arange(10)
tang_array.shape
>(10,)
tang_array = tang_array[: , np.newaxis]      #10X1的矩阵
tang_array.shape
>(10, 1)

必须注意增加维度的位置。

5、矩阵的转置

tang_array.transpose()    #转置
tang_array.T                    #转置

6、数据的连接

a = np.array([[123,456,678],[3214,456,134]])
a
>array([[ 123,  456,  678],
        [3214,  456,  134]])
b = np.array([[1235,3124,432],[43,13,134]])
b
>array([[1235, 3124,  432],
        [  43,   13,  134]])
c = np.concatenate((a,b))
c
>array([[ 123,  456,  678],
       [3214,  456,  134],
       [1235, 3124,  432],
       [  43,   13,  134]])

c = np.concatenate((a,b),axis = 0)
c
>array([[ 123,  456,  678],
        [3214,  456,  134],
        [1235, 3124,  432],
        [  43,   13,  134]])
        
c = np.concatenate((a,b),axis = 1)
c
array([[ 123,  456,  678, 1235, 3124,  432],
       [3214,  456,  134,   43,   13,  134]])

axis=0时按列拼接,axis=1按行拼接

7、构建0/1数组

np.zeros((3,3))
>array([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])
        
np.ones((3,3))
>array([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
        
np.ones((3,3)) * 8
>array([[ 8.,  8.,  8.],
        [ 8.,  8.,  8.],
        [ 8.,  8.,  8.]])

也可以构建维度相同的矩阵:

w2 = np.zeros_like(w1)     #w1和w2维度相同,w2用0填充

8、矩阵的运算

x = np.array([5,5])
y = np.array([2,2])
np.multiply(x,y)     #对应元素相乘
>array([10, 10])
np.dot(x,y)            #矩阵的乘法(当xy为一维向量是内积运算)
>20

逻辑运算:

#逻辑与、或、非
np.logical_and(x,y)
np.logical_or(x,y)
np.logical_not(x,y)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值