Python--numpy教程

1.Numpy简介

numpy是python中用于科学计算的核心库。它提供了高性能的多维数组的对象,以及相关工具。

2.创建数组

一维数组:

import numpy as np
>>> a = np.array([1, 2, 3])
>>> print(type(a))
<class 'numpy.ndarray'>
>>> print(a.shape)
(3,)#元素个数
>>> print(a[0])
1
>>> a[0]=8
>>> print(a)
[8 2 3]

二维数组:

 b = np.array([[1,2,3],[4,5,6]])
>>> print(b.shape)
(2, 3)#2行3列
>>> b = np.array([[1,2,3],[4,5,6]])
>>>print(b[0,0])
1
>>> print(b[0,1])
2
>>>print(b[1,0])
4

3.数组访问

1.切片访问:

import numpy as np
>>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> b = a[:2, 1:3]
>>> print(b)
[[2 3]
 [6 7]]
>>> print(a[0, 1])
2
>>> print(b[0, 0])
2

>>> row_r1 = a[1, :]
>>> row_r2 = a[1:2, :]
>>> print(row_r1, row_r1.shape)
[5 6 7 8] (4,)
>>> print(row_r2, row_r2.shape)
[[5 6 7 8]] (1, 4)
>>> col_r1 = a[:, 1]
>>> col_r2 = a[:, 1:2]
>>> print(col_r1, col_r1.shape)
[ 2  6 10] (3,)
>>> print(col_r2, col_r2.shape)
[[ 2]
 [ 6]
 [10]] (3, 1)

2.整型数组访问
构建成一个新数组:

>>> a = np.array([[1,2],[3,4],[4,5]])
>>> print(a[[0,1,2],[0,1,0]])
[1 4 4]
>>> print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
[1 4 4]
>>> print(a[[0, 0], [1, 1]])
[2 2]
>>> print(np.array([a[0, 1], a[0, 1]]))
[2 2]

4.数据类型

>>> import numpy as np
>>> x = np.array([1, 2])
>>> print(x.dtype)
int32#和电脑位数没有关系
>>> x = np.array([1.0, 2.0])
>>> print(x.dtype)
float64
>>> x = np.array([1 ,2], dtype=np.int64)
>>> print(x.dtype)
int64

5.数组计算

1.基本运算

>>> import numpy as np
>>> a = np.arange(24)
>>> a = a.reshape(4,6)
>>> print(a)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]
>>> b = a-2
>>> print(b)
[[-2 -1  0  1  2  3]
 [ 4  5  6  7  8  9]
 [10 11 12 13 14 15]
 [16 17 18 19 20 21]]
>>> print(a*b)#矩阵卷积运算
[[  0  -1   0   3   8  15]
 [ 24  35  48  63  80  99]
 [120 143 168 195 224 255]
 [288 323 360 399 440 483]]
#矩阵相乘
>>> import numpy as np
>>> a = np.arange(24)
>>> a = a.reshape(4,6)
>>> print(a)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]
>>> b = a-2
>>> print(b)
>>> c = b.T
[[  25  115  205  295]
 [  43  349  655  961]
 [  61  583 1105 1627]
 [  79  817 1555 2293]]
>>> print(np.dot(a,c))
[[-2 -1  0  1  2  3]
 [ 4  5  6  7  8  9]
 [10 11 12 13 14 15]
 [16 17 18 19 20 21]]

2.矩阵转置

>>> import numpy as np
>>> a = np.array([[0, 1],[2, 3]])
>>> print(a)
[[0 1]
 [2 3]]
>>> print(a.T)
[[0 2]
 [1 3]]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值