## 2017年8月3日 星期四

### [ Python 常見問題 ] Numpy - From ND to 1D arrays

Source From Here
Question
Say I have an array a:
1. a = np.array([[1,2,3], [4,5,6]])
I would like to convert it to a 1D array (i.e. a column vector).

How-To
Use np.ravel (for a 1D view) or np.flatten (for a 1D copy) or np.flat (for an 1D iterator):
>>> import numpy as np
>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])

>>> b = a.ravel()
>>> b
array([1, 2, 3, 4, 5, 6])
>>> b[0]
1

Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]). If you want a copy rather than a view, use:
>>> c = a.flatten()
>>> c
array([1, 2, 3, 4, 5, 6])
>>> c[0] = 10
>>> c
array([10, 2, 3, 4, 5, 6])
>>> a // Modify c won't update a
array([[1, 2, 3],
[4, 5, 6]])

If you just want an iterator, use np.flat:
>>> for i in d:
... print(i)
...
>>> for i in a.flat:
... print(i)
...
1
2
3
4
5
6

### [ FP In Python ] Ch1. (Avoiding) Flow Control

Preface   In typical imperative Python programs—including those that make use of classes and methods to hold their imperative code—a block...