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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...