Numpy基础学习笔记

Numpy学习笔记

by 熠熠发光的白

1.导入包
import numpy as np
2.基础操作
a = np.arange(15) #建造一个一维的,有从0到14的array
a = a.reshape(3, 5) #重塑为3×5的矩阵
print(a.shape) #显示形状
print(a.size) #显示具体尺寸
print(a.dtype) # 描述array的类型
print(a.itemsize) #描写每个数据占据的字节数
print(a.data) #表示其buffer data

(3, 5)
15
int32
4
<memory at 0x000001FAFA240520>

3.创建
a = np.array([1, 2, 3, 4])
print(a)
b = np.array([(1, 5, 2, 3), (4, 5, 6)]) #这里会有个warning,因为list的维度不同
print(b)
c = np.array([[1, 2], [3, 4]], dtype=complex)
print(c)

#用占位符来创建已知尺寸的数组
a = np.zeros((3, 4)) #全部赋值为0
print(a)
a = np.ones((2, 3, 4), dtype=np.int16) #全部赋值为1
print(a)
a = np.empty((2, 3)) #根据内存状态随机初始化数组
print(a)
a = np.arange(10, 30, 5) #10到25,5步一隔
print(a)
a = np.arange(0, 2, 0.3) #0到2,0.3步一隔
print(a)
a = np.linspace(0, 2, 9) #0到2,选取9个数字
print(a)

[1 2 3 4]
[(1, 5, 2, 3) (4, 5, 6)]
[[1 2]
[3 4]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
[[0. 0. 0.]
[0. 0. 0.]]
[10 15 20 25]
[0. 0.3 0.6 0.9 1.2 1.5 1.8]
[0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]

4.基础运算
a = np.array([20, 30, 40, 50])
b = np.arange(4) #生成0—3的array
print(a-b)
print(b**2)
print(10*np.sin(a))
print(a<35)
print(a*b) #这里是分开的元素相乘

#矩阵乘法
A = np.array([[1, 1], [0, 1]])
B = np.array([[2, 0], [3, 4]])
print(A*B)
print(A@B)
print(A.dot(B)) #矩阵乘法

[20 29 38 47]
[0 1 4 9]
[ 9.12945251 -9.88031624 7.4511316 -2.62374854]
[ True True False False]
[ 0 30 80 150]
[[2 0]
[0 4]]
[[5 4]
[3 4]]
[[5 4]
[3 4]]

5.自操作逻辑
a = np.arange(6)
print(a)
print(a.sum())
print(a.min())
print(a.max())
b = np.arange(12).reshape(3, 4)
print(b)
print(b.sum(axis=0))
print(b.min(axis=1))
print(b.cumsum(axis=1)) #逐层累加

#加减操作
a = np.arange(3)
print(np.exp(a))
print(np.sqrt(a))
b = np.array([1, -2, 5])
print(np.add(a, b))

[0 1 2 3 4 5]
15
0
5
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[12 15 18 21]
[0 4 8]
[[ 0 1 3 6]
[ 4 9 15 22]
[ 8 17 27 38]]

[1. 2.71828183 7.3890561 ]
[0. 1. 1.41421356]
[ 1 -1 7]

6.迭代,切片与标记
a = np.arange(10)**3
print(a)
print(a[2])
print(a[2:5])
a[:6:2] = 1000
print(a)
print(a[::-1]) #翻转输出
for i in a
	print(i)

#切片
def f(x, y):
    return 10*x+y
b = np.fromfunction(f, (5, 4), dtype=int) #形成函数
print(b)
print(b[2, 3])
print(b[2][3]) #这两句意思一致
print(b[0:5, 1])
print(b[:, 1])
print(b[1:3, :])
print(b[-1]) #打印最后一行

c = np.array([
    [0, 1, 2],
    [10, 12, 13],
    [100, 101, 102],
    [110, 112, 113]
])
print(c)
print(c[1, ...]) #打印行
print(c[..., 2]) #打印列

[ 0 1 8 27 64 125 216 343 512 729]
8
[ 8 27 64]
[1000 1 1000 27 1000 125 216 343 512 729]
[ 729 512 343 216 125 1000 27 1000 1 1000]
1000
1
1000
27
1000
125
216
343
512
729

[[ 0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]]
23
23
[ 1 11 21 31 41]
[ 1 11 21 31 41]
[[10 11 12 13]
[20 21 22 23]]
[40 41 42 43]
[[ 0 1 2]
[ 10 12 13]
[100 101 102]
[110 112 113]]
[10 12 13]
[ 2 13 102 113]

7.图形变换
a = np.array([[3., 7., 3., 4.],
              [1., 4., 2., 2.],
              [7., 2., 4., 9.]
             ])
print(a)
print(a.shape)

#改变形状
print(a.ravel()) #将a的所有元素铺成一维
print(a.reshape(6, 2))
print(a.T)
print(a.reshape(3, -1)) #-1表示自动计算维度值

[[3. 7. 3. 4.]
[1. 4. 2. 2.]
[7. 2. 4. 9.]]
(3, 4)
[3. 7. 3. 4. 1. 4. 2. 2. 7. 2. 4. 9.]
[[3. 7.]
[3. 4.]
[1. 4.]
[2. 2.]
[7. 2.]
[4. 9.]]
[[3. 1. 7.]
[7. 4. 2.]
[3. 2. 4.]
[4. 2. 9.]]
[[3. 7. 3. 4.]
[1. 4. 2. 2.]
[7. 2. 4. 9.]]

8. vstack和hstack
a = np.array([[9., 7.], [5., 2.]])
b = np.array([[1., 9.], [5., 1.]])
print(np.vstack((a, b))) #纵向堆叠 vertical,形成a在上,b在下的关系
print(np.hstack((a, b))) #横向堆叠 horizonal,将b放在a的右边
print(np.dstack((a, b))) #deep stack,产生新的维度

[[9. 7.]
[5. 2.]
[1. 9.]
[5. 1.]]
[[9. 7. 1. 9.]
[5. 2. 5. 1.]]

[[[9. 1.]
[7. 9.]]

[[5. 5.]
[2. 1.]]]

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

c = np.c_[a, b] #纵向堆叠
d = np.r_[a, b] #横向堆叠
print(c)
print(d)

[[1 2 3 4 5 6]
[7 8 9 1 2 3]]
[[1 2 3]
[7 8 9]
[4 5 6]
[1 2 3]]

10. hsplit、vsplit、array_split
a = np.floor(10 * np.random.random((2, 6)))
print(a)
print(np.hsplit(a, 3)) #拆分成3份
print(np.hsplit(a, (2, 4, 5))) #在0-1,2-3,4,5这样分割

#vsplit
a = np.arange(16).reshape([4, 4])
print(a)
print(np.vsplit(a, 2))
print(np.vsplit(a, (2, 3)))#0-1, 2, 3

#array_split(与另外两个的区别在于不是整除的也可以被分割)
a = np.arange(8)
print(a)
print(np.array_split(a, 3))

[[6. 6. 0. 7. 5. 9.]
[6. 7. 9. 7. 0. 2.]]
[array([[6., 6.],
[6., 7.]]), array([[0., 7.],
[9., 7.]]), array([[5., 9.],
[0., 2.]])]
[array([[6., 6.],
[6., 7.]]), array([[0., 7.],
[9., 7.]]), array([[5.],
[0.]]), array([[9.],
[2.]])]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]]), array([[12, 13, 14, 15]])]

[0 1 2 3 4 5 6 7]
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7])]

11.浅拷贝和深拷贝
a = np.array([
    [1, 2, 3, 4],
    [4, 3, 2, 1],
    [2, 3, 4, 1],
    [3, 4, 1, 2]
])
c = a.view()
print(c is a) #c和a不是一样的东西
print(c.base is a) #c是基于a的浅拷贝
print(c.flags.owndata) #c不拥有数据
print(a.flags.owndata) #a拥有数据
s = a[:, 1:3] #取a中的一段
s[:] = 10 #将它全部赋值为10
print(a) #发现a产生变化了

False
True
False
True
[[ 1 10 10 4]
[ 4 10 10 1]
[ 2 10 10 1]
[ 3 10 10 2]]

d = a.copy()
print(d is a)
print(d.base is a)
print(d.flags.owndata)

False
False
True

可见,在之后调用的时候,应该先用copy将切片提取出来再进行数据处理

12.布尔列表索引
a = np.arange(12)**2
i = np.array([1, 2, 3, 8, 5])
print(a[i])
j = np.array([[3, 4], [9, 7]])
print(a[j])

[ 1 4 9 64 25]
[[ 9 16]
[81 49]]

#一个图片的示例
palette = np.array([[0, 0, 0],         # black
                    [255, 0, 0],       # red
                    [0, 255, 0],       # green
                    [0, 0, 255],       # blue
                    [255, 255, 255]])  # white
image = np.array([[0, 1, 2, 0],        # each value corresponds to a color in the palette
                  [0, 3, 4, 0]])
palette[image]                         # the (2, 4, 3) color image

array([[[ 0, 0, 0],
[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0]],

[[ 0, 0, 0],
[ 0, 0, 255],
[255, 255, 255],
[ 0, 0, 0]]])

a = np.arange(12).reshape(3, 4)
print(a)
i = np.array([[0, 1], [1, 2]])
j = np.array([[2, 1], [3, 3]])
print(a[i, j])
print(a[i, 2])
print(a[:, j]) #不明输出结果,以后再思考,,
time = np.linspace(20, 145, 5)
data = np.sin(np.arange(20)).reshape(5, 4)
print(time)
print(data)
ind = data.argmax(axis=0)
print(ind) #读出一行最大值的index
data_max = data[ind, range(data.shape[1])]
print(data_max)
print(data.max(axis=0))
print(np.all(data_max == data.max(axis=0)))

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

[[ 6 5]
[ 7 7]]

[[10 9]
[11 11]]]
[ 20. 51.25 82.5 113.75 145. ]
[[ 0. 0.84147098 0.90929743 0.14112001]
[-0.7568025 -0.95892427 -0.2794155 0.6569866 ]
[ 0.98935825 0.41211849 -0.54402111 -0.99999021]
[-0.53657292 0.42016704 0.99060736 0.65028784]
[-0.28790332 -0.96139749 -0.75098725 0.14987721]]
[2 0 3 1]
[0.98935825 0.84147098 0.99060736 0.6569866 ]
[0.98935825 0.84147098 0.99060736 0.6569866 ]
True

a = np.arange(5)
print(a)
a[[1, 3, 4]]=0
print(a)

a = np.arange(5)
a[[0, 0, 2]] = [1, 2, 3] #赋值有重复的时候,只会留下最后的赋值
print(a)

a = np.arange(5)
a[[0, 0, 2]] += 1 #对于重复的+=1也只运行一次
print(a)

[0 1 2 3 4]
[0 0 2 0 0]
[2 1 3 3 4]
[1 1 3 3 4]

13.布尔矩阵和索引
a = np.arange(12).reshape(3, 4)
b = a > 4
print(b)
print(a[b])
a[b] = 0
print(a)

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

14.ix_功能
a = np.array([2, 3, 4, 5])
b = np.array([8, 5, 4])
c = np.array([5, 4, 6, 8, 3])
ax, by, cz = np.ix_(a, b, c)
print(ax)
print(by)
print(cz)

result = ax + by * cz
print(result)

print(result[3, 2, 4]) #a[3]+b[2]*c[4]

[[[2]]

[[3]]

[[4]]

[[5]]]
[[[8]
[5]
[4]]]
[[[5 4 6 8 3]]]
[[[42 34 50 66 26]
[27 22 32 42 17]
[22 18 26 34 14]]

[[43 35 51 67 27]
[28 23 33 43 18]
[23 19 27 35 15]]

[[44 36 52 68 28]
[29 24 34 44 19]
[24 20 28 36 16]]

[[45 37 53 69 29]
[30 25 35 45 20]
[25 21 29 37 17]]]

17

15.ufunc_reduce功能

上图功能也可以这样进行简化

def ufunc_reduce(ufct, *vectors):
    vs = np.ix_(*vectors)
    r = ufct.identity
    return

for v in vs:
    r = ufct(r, v)
    return r

ufunc_reduce(np.add, a, b, c)

这个的优势在于利用了广播法则,避免创建了输出大小×向量个数的参数数组

16.线性代数部分
a = np.array([[1, 2], [3, 4]])
print(a.transpose()) #转置
print(np.linalg.inv(a)) #求逆矩阵
u = np.eye(2)
print(u) #一个对角矩阵,主对角线为1,其余都是0
j = np.array([[0., -1.], [1., 0.]])
print(j @ j) #返回j和j的点乘
print(np.trace(u)) #返回对角线上的数字和
y = np.array([[5.], [7.]])
print(np.linalg.solve(a, y)) #解方程ax = y
print(np.linalg.eig(j)) #计算方程的特征向量,第一个元素是特征值,第二个元素是对应的特征向量

[[1 3]
[2 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
[[1. 0.]
[0. 1.]]
[[-1. 0.]
[ 0. -1.]]
2.0
[[-3.]
[ 4.]]
(array([0.+1.j, 0.-1.j]), array([[0.70710678+0.j , 0.70710678-0.j ],
[0. -0.70710678j, 0. +0.70710678j]]))

17.直方图绘制
import numpy as np
rg = np.random.default_rng(1)
import matplotlib.pyplot as plt
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = rg.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
plt.hist(v, bins=50, density=1)       # matplotlib version (plot)直方图
# Compute the histogram with numpy and then plot it
(n, bins) = np.histogram(v, bins=50, density=True)  # NumPy version (no plot)
plt.plot(.5*(bins[1:]+bins[:-1]), n)  #折线图(计算平均值)
plt.show()

在这里插入图片描述

实践-绘制曼德布罗特集合
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
    """Returns an image of the Mandelbrot fractal of size (h,w)."""
    y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
    c = x+y*1j
    z = c
    divtime = maxit + np.zeros(z.shape, dtype=int)

    for i in range(maxit):
        z = z**2 + c
        diverge = z*np.conj(z) > 2**2            # who is diverging
        div_now = diverge & (divtime==maxit)  # who is diverging now
        divtime[div_now] = i                  # note when
        z[diverge] = 2                        # avoid diverging too much

    return divtime

plt.imshow(mandelbrot(400,400))
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值