# 科学计算5 - Numpy 高级

2018-02-08
Geng

## Copies and views

### Views

import numpy as np

a = np.arange(10)
a

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

b = a[::2]
b

array([0, 2, 4, 6, 8])

b[0] = 10
b # b 变了

array([10,  2,  4,  6,  8])

a # a 也变了

array([10,  1,  2,  3,  4,  5,  6,  7,  8,  9])

np.may_share_memory(a, b)

True


### Copies

c = b.copy() # 使用copy创建一块儿新的内存
np.may_share_memory(c, b)

False


### 试试这两个语句

a = np.ones((2,2))
ref = a
ref

array([[ 1.,  1.],
[ 1.,  1.]])

deep_copy = np.zeros((2,2))
deep_copy[:] = a
deep_copy

array([[ 1.,  1.],
[ 1.,  1.]])

np.may_share_memory(ref, a)

True

np.may_share_memory(deep_copy, a)

False


## Fancy indexing

Numpy数组可以采用切割的方法索引, 也可以采用布尔方式(或者掩模 mask). 这种方法叫做花式索引(fancy indexing). 它创建的是副本而不是view

a = np.arange(10)
d = a[a % 2 == 0]
d

array([0, 2, 4, 6, 8])

np.shares_memory(a, d)

False


### 采用整数数组索引

a = np.arange(0, 100, 10)
a[[1,2,2,2,3,2]]

array([10, 20, 20, 20, 30, 20])


a = np.arange(10)
idx = np.array([[2,3], [7,9]])
a[idx]

array([[2, 3],
[7, 9]])


## numpy数组添加更多元素

How to add items into a numpy array

ppending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you’ll quickly discover that NumPy doesn’t easily or efficiently do this the way a python list will. You’ll find that every “append” action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It’s often unavoidable and the functions that do this are:

for 2-D arrays:

for 3-D arrays (the above plus):

for N-D arrays: