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


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...