1. 创建numpy数组
1.1 通过tuple和list创建数组
import numpy as np
通过tuple
t=(1,2,3)
a=np.array(t,dtype= 'int')
#array([1, 2, 3])
通过list
list1 = [1,2,3]
a = np.array(list1,dtype='int')
#array([1, 2, 3])
用多个list创建多维数组
list1 = [1,2,3]
list2 = [4.2,5.1,6.3]
b = np.array([list1,list2])
#array([[1. , 2. , 3. ],
[4.2, 5.1, 6.3]])
b.dtype
#dtype('float64')
改变dtype
c = np.array( [ [1,2], [3,4] ], dtype=complex )
#array([[1.+0.j, 2.+0.j],
[3.+0.j, 4.+0.j]])
c.shape
#(2, 2)
1.2 创建特殊数组
np.zeros([2,4])
#array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
np.ones([2,3])
#array([[ 1., 1., 1.],
[ 1., 1., 1.]])
np.empty([3,2])
#array([[1., 1.],
[1., 1.],
[1., 1.]])
#return a new array of given shape and type, without initializing entries.
np.eye(3)
#array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
np.arange(2,10,2)
#array([2, 4, 6, 8])
np.linspace(0,10,4)
#array([ 0., 3.33333333, 6.66666667, 10.])
#4 numbers from 0 to 10 , 等分
np.linspace(0,10,3)
#array([ 0., 5., 10.])
2. numpy数组的基本运算
2.1 算术运算
a = np.array([[1,2,3],[4,5,6]])
#array([[1, 2, 3],
[4, 5, 6]])
a * a
#array([[ 1, 4, 9],
[16, 25, 36]])
a ** 3
#array([[ 1, 8, 27],
[ 64, 125, 216]], dtype=int32)
a + a
#array([[ 2, 4, 6],
[ 8, 10, 12]])
1/a
#array([[1. , 0.5 , 0.33333333],
[0.25 , 0.2 , 0.16666667]])
2.2 矩阵运算
A = np.array( [[1,3],[0,1]] )
B = np.array( [[2,2],[3,4]] )
#array([[1, 3],
[0, 1]])
#array([[2, 2],
[3, 4]])
矩阵相乘
np.dot(A, B) #A.dot(B)
#array([[11, 14],
[ 3, 4]])
#A*B是元素相乘,两者不同
矩阵相加
np.add(A, B)
#array([[3, 5],
[3, 5]])
2.3 其他运算
a = np.random.random([3,3])
array([[0.19176092, 0.92224897, 0.61994304],
[0.80936465, 0.02533119, 0.72779562],
[0.29421129, 0.35640441, 0.87175173]])
# np.random.random是在[0.0, 1.0) 之间生成随机数字
a.sum()
4.818811836180757
a.min()
0.025331193574141042
a.max()
0.9222489672128614
np.random.randn(3,3)
array([[ 0.94114569, -1.11281987, -0.16988063],
[ 0.11768634, 0.16164328, -0.15441487],
[-0.18021596, -0.46057389, -0.80320574]])
# 以0为中心的高斯分布
np.random.normal([1,2,3])
array([ 1.49216002, 4.30790776, 2.59977786])
# 正太分布numpy.random.normal(loc=0.0, scale=1.0, size=None)
b = np.arange(24).reshape(6,4)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
# 关于 axis: axis=0 是沿着列操作 axis=1 是沿着行操作
b.sum(axis=0)
array([60, 66, 72, 78])
b.sum(axis=1)
array([ 6, 22, 38, 54, 70, 86])
b.min(axis=1)
array([ 0, 4, 8, 12, 16, 20])
b.cumsum(axis=1) # 累计相加 cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38],
[12, 25, 39, 54],
[16, 33, 51, 70],
[20, 41, 63, 86]], dtype=int32)
本文介绍了使用Python的NumPy库创建数组的方法,包括通过tuple和list创建数组、创建特殊数组如zeros和ones等,并详细讲解了数组的基本运算,如算术运算、矩阵运算以及其他常用操作。
799

被折叠的 条评论
为什么被折叠?



