Numpy 学习笔记

1. Array创建

import numpy as np
import pandas as pd

# Array creation
# 指定数组元素
np.array([1,2,3,4,5])
np.array([[1,2,3],
              [4,5,6]])

# identity matrix
np.eye(4)

# 指定数据类型
np.array([[1,2,3],
               [4,5,6]],dtype='float')
# complex number
np.array([[1+3j,4+5j],
              [2.1+4j,5]],dtype='complex')

# 零数组
np.zeros((4,3))

# 全1数组
np.ones((5,4),dtype='int16')

# empty数组,数值是一个很小的数
np.empty((5,4))

# 随机数组(从[0,1)均匀分布抽)
np.random.rand(5,4)

# 随机数组(从正态分布抽)
np.random.randn(5,4)

# 随机整数数组,第一个和第二个参数是整数取值范围(端点可取),第三个参数是维数
np.random.random_integers(-1,5,(2,2))

# 创建等差数组,类似于range()
np.arange( 10, 30, 5 )
np.arange( 0, 2, 0.3 )  

# 在指定的间隔内返回均匀间隔的数字
np.linspace( start=0, stop=2, num=9 ) 

# 利用fromfunction
def func(i,j):
    return i*j
np.fromfunction(func,(5,4),dtype='int32')
# 输出
array([[ 0,  0,  0,  0],
       [ 0,  1,  2,  3],
       [ 0,  2,  4,  6],
       [ 0,  3,  6,  9],
       [ 0,  4,  8, 12]])

2. 索引、切片和迭代

2.1. 一般索引

# One dimensional array
a = np.arange(10)     # array 0-9
a[2]                  # 输出2
a[2:5]                # 输出array([2, 3, 4])
a[:6:2]               # 输出array([0, 2, 4]);相当于a[0:6:2]
a[::-1]               # 将a反向输出;9-0


# Multidimensional array
def func(i,j):
    return 10*i+j
b = np.fromfunction(func,(5,4),dtype='int32')
b[2,3]                # 23
b[0:5, 1]             # 输出第二列
b[:,1]                # 输出第二列
b[1:3,:]              # 输出第二行到第三行
b[:,1:3]              # 输出第二列到第三列
b[-2]                 # 输出倒数第2行;相当于b[-2,:]
b[-4:-2,:]            # 输出倒数第四行到倒数第三行

2.2. 高级索引

Indexing with Arrays of Indices

c = np.arange(12)**2
indx_c = np.array([[2,1],[4,3]])
c[indx_c]                          # the same shape as indx_c
#array([[ 4,  1],
#      [16,  9]])

d = np.arange(20).reshape(5,4)
indx_i = np.array([[2,1], [4,3]])  # 第一维的坐标
indx_j = np.array([[0,3], [2,3]])  # 第二维的坐标
d[indx_i,indx_j]                   # same shape as indx_i
d[[indx_i,indx_j]]                 # 和上面相同
d[:,indx_j]                        # 52 by 2 的数组
d[indx_i,2]                        # 固定第二个维数,2 by 2数组
d[indx_i]                          # 22 by 4 数组
d[[2,3,0,1],range(d.shape[1])]     # 长度为4的数组

# assignment
a = np.arange(5)
a[[0,1,2]]=0                       # array([0, 0, 0, 3, 4])
a = np.arange(5)
a[[0,0,2]]=[11,22,3]               # array([22,  0,  3,  3,  4])
a = np.arange(5)
a[[0,1,2]]=a[[0,1,2]]+1            # array([1, 2, 3, 3, 4])

Indexing with Boolean Arrays

# Boolean array
a = np.random.randn(5,4)
b = a.copy()
a[a<0] = 0                         # a中小于0的全部设置为0

indx_b1 = np.array([True, False, False, True, True])
indx_b2 = np.array([False, False, True, False])

b[indx_b1]                         # 取第1,4,5行
b[indx_b1,:]                       # 一样
b[:,indx_b2]                       # 取第三列

3. 运算

a = np.arange(16).reshape(4,4)
# transpose
a.T
a.transpose()
#inverse
np.linalg.inv(a)
# 矩阵乘法
np.dot(a,a)
# trace
np.trace(a)
# eigen values and vectors
np.linalg.eig(a)
# 解线性方程组ax=b
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)

4. Shape Manipulation

a = np.arange(12).reshape(4,3)
a.shape                        # (4, 3)
a.ravel()                      # flatten the array, a不改变
a.reshape(3,4)                 # a 不改变
a.resize(2,6)                # a 改变了


# 连接两个2-D数组,或者连接一个2-D数组和一个1-D数组
a = np.array([[2,3,4],[11,12,13]])
b = np.array([[1,1,1],[2,2,2]])
np.vstack((a,b))               # 沿纵向接
np.row_stack((a,b))
# array([[ 2,  3,  4],
#        [11, 12, 13],
#        [ 1,  1,  1],
#        [ 2,  2,  2]])
np.hstack((a,b))               # 沿水平方向接
np.column_stack((a,b))
# array([[ 2,  3,  4,  1,  1,  1],
#        [11, 12, 13,  2,  2,  2]])

# 连接两个1-D array
a=np.array([4.,3.])
b=np.array([2.,8.])
np.column_stack((a[:,np.newaxis],b[:,np.newaxis]))
np.hstack((a[:,np.newaxis],b[:,np.newaxis])) 
# array([[ 4.,  2.],
#        [ 3.,  8.]])
np.vstack((a[:,np.newaxis],b[:,np.newaxis]))
# array([[ 4.],
#        [ 3.],
#        [ 2.],
#        [ 8.]])

5. 复制和View

View or Shallow Copy

>>> c = a.view()                       # c is a view of the data 
>>> c is a
False
>>> c.shape = 2,6                      # a's shape doesn't change
>>> a.shape
(3, 4)
>>> c[0,4] = 1234                      # a's data changes
>>> a
array([[   0,    1,    2,    3],
       [1234,    5,    6,    7],
       [   8,    9,   10,   11]])


# Slicing an array returns a view of it:
>>> s = a[ : , 1:3]     
>>> s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
>>> a                   # a changed
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])

Deep Copy

>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a                           # d doesn't share anything with a
False
>>> d[0,0] = 9999
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值