numpy-n2

作者: 若缘生 | 来源:发表于2018-07-12 22:09 被阅读0次

[TOC]
说明:本文是numpy入门的第二篇笔记。


numpy的智能切片

numpy提供了比原始python强大的多的切片功能。

1. 利用array来切片

import numpy as np
a = np.arange(12)**2
i = np.array([1,1,3,8,5])
a[i] # 切出a数组中位置为1,1,3,8,5处的元素。没有形成新对象!!!都是按照第0维来切。
array([ 1,  1,  9, 64, 25], dtype=int32)
a.resize(6,2)
a
array([[  0,   1],
       [  4,   9],
       [ 16,  25],
       [ 36,  49],
       [ 64,  81],
       [100, 121]], dtype=int32)
i = np.array([1,1,2,4,3,2])
a[i] # 果然是按照第零维切出的!!!
array([[ 4,  9],
       [ 4,  9],
       [16, 25],
       [64, 81],
       [36, 49],
       [16, 25]], dtype=int32)
j = np.array([[1,2],[3,4]])
a[j]  # 看,还是按照第零维切出,只不过按照j的形状重组了。
array([[[ 4,  9],
        [16, 25]],

       [[36, 49],
        [64, 81]]], dtype=int32)
# 同样的,可以使用双下标来索引多维数组,要求双下标的形状是一样的
a = np.arange(12).reshape(3,4)
a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
i = np.array([[0,1],[1,2]])
j = np.array([[2,1],[3,3]])
a[i,j]
array([[ 2,  5],
       [ 7, 11]])
a[i,2]
array([[ 2,  6],
       [ 6, 10]])
a[:,j]
array([[[ 2,  1],
        [ 3,  3]],

       [[ 6,  5],
        [ 7,  7]],

       [[10,  9],
        [11, 11]]])
# 同样,可以将组合的数组添加新的标签,然后索引。
ll = [i,j]
a[ll]
array([[ 2,  5],
       [ 7, 11]])
# 同样,可以利用array作为数组的指标。进行索引、复制。
a = np.arange(5)
a[[0,0,2]]+=1
a
array([1, 1, 3, 3, 4])

2. bool值作为指标

a = np.arange(12).reshape(3,4)
b = a > 4
b
array([[False, False, False, False],
       [False,  True,  True,  True],
       [ True,  True,  True,  True]])
a[b]# 选出大于4的值
array([ 5,  6,  7,  8,  9, 10, 11])
a[b] = 0 # 将大于4的值置为0
a
array([[0, 1, 2, 3],
       [4, 0, 0, 0],
       [0, 0, 0, 0]])

简单实例——Mandelbrot set生成

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot(h, w, maxit = 20):
    """Return an image of the Madelbrot 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
        div_now = diverge & (divtime==maxit)
        divtime[div_now] = i
        z[diverge] = 2
    return divtime
plt.imshow(mandelbrot(400,400))
plt.show()
output_17_0.png

numpy做代数运算

a = np.array([[1.0,2.0],[3,4]])
a
array([[1., 2.],
       [3., 4.]])
a.transpose()#转置
array([[1., 3.],
       [2., 4.]])
b = np.linalg.inv(a) # 生成逆矩阵
b
array([[-2. ,  1. ],
       [ 1.5, -0.5]])
u = np.eye(2) #生成单位阵
u
array([[1., 0.],
       [0., 1.]])
c = np.dot(a,b) #矩阵乘法 c=a.dot(b)
c
array([[1.0000000e+00, 0.0000000e+00],
       [8.8817842e-16, 1.0000000e+00]])
np.trace(a) #矩阵的迹
5.0
y = np.array([[5.],[7.]])
x = np.linalg.solve(a,y) #求解线性方程组
x
array([[-3.],
       [ 4.]])
np.linalg.eig(a)# 特征值
(array([-0.37228132,  5.37228132]), array([[-0.82456484, -0.41597356],
        [ 0.56576746, -0.90937671]]))

相关文章

  • numpy-n2

    [TOC]说明:本文是numpy入门的第二篇笔记。 numpy的智能切片 numpy提供了比原始python强大的...

网友评论

    本文标题:numpy-n2

    本文链接:https://www.haomeiwen.com/subject/wrkdpftx.html