Numpy 中数组和矩阵的基本运算

1.建立矩阵

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


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

#O:     [[1 2 3]
         [1 2 3]]

----------
b = np.arange(12)
print b

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


----------
b = np.arange(12).reshape(3,4)
print b

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


----------
b = np.eye(3,3)
print b
#O:     [[ 1.  0.  0.]
         [ 0.  1.  0.]
         [ 0.  0.  1.]]


----------
c = np.eye(3,5)
print c
#O      [[ 1.  0.  0.  0.  0.]
         [ 0.  1.  0.  0.  0.]
         [ 0.  0.  1.  0.  0.]]

2.矩阵维度

import numpy as np

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


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

3.求和,极值

b = np.arange(12).reshape(3, 4)
print b.sum()
#O      66

print b.max()
#O      11

print b.min()
#O  0

print b.mean()
#O      5.5

test1 = np.array([[5, 10, 15],
            [20, 25, 30],
            [35, 40, 45]])
#行求和
test1.sum(axis=1)
# 输出 array([30, 75, 120])

#列求和
test1.sum(axis=0)
# 输出 array([60, 75, 90])

4.数组乘法

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

#按元素相乘 elementwise
print a*b

#输出     [[ 5 12]
         [21 32]]


#矩阵乘法
print a.dot(b)
#输出     [[19 22]
         [43 50]]

5.元素运算

a = np.arange(4)
print a
print a**2                  #square
print np.exp(a)             #power of E
print np.sqrt(a)            #root
print np.floor(np.sqrt(a))  #round

#OUT    [0 1 2 3]
        [0 1 4 9]
        [  1.           2.71828183   7.3890561   20.08553692]
        [ 0.          1.          1.41421356  1.73205081]
        [ 0.  1.  1.  1.]

6.转置

a = np.arange(12).reshape(3, 4)
b = a.T
print a
print b

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

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

7.数组删除指定,行列

z= np.arange(10).reshape(5, 2)
print z
z = np.delete(z, np.s_[1:3],axis = 0)
print z

#OUT    [[0 1]
         [2 3]
         [4 5]
         [6 7]
         [8 9]]

        [[6 7]
         [8 9]]

z = np.delete(z, np.s_[0,2],axis = 0)
print z

#OUT    [[2 3]
         [6 7]
         [8 9]]



z= np.arange(10).reshape(2, 5)
print z
z = np.delete(z, np.s_[0:2],axis = 1)
print z


#OUT    [[0 1 2 3 4]
         [5 6 7 8 9]]
        [[2 3 4]
         [7 8 9]]

8.矩阵拼接

import numpy as np
a = [[1, 2, 3],
     [1, 2, 3]]
b = [[4,4,4],
    [4,4,4]]

c = np.row_stack((a, b))
print c
c = np.column_stack((a, b))
print c     

#OUT    [[1 2 3]
         [1 2 3]
         [4 4 4]
         [4 4 4]]

        [[1 2 3 4 4 4]
         [1 2 3 4 4 4]]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值