2020年10月1日 星期四

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

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

HowTo
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
  1. >>> ex1 = ary.reshape(1, -1)  
  2. >>> ex1  
  3. array([[1, 2, 3, 4, 5, 6]])  
  4. >>> ex1.shape  
  5. (1, 6)  
  6.   
  7. >>> ex2 = ary.ravel()  
  8. >>> ex2  
  9. array([1, 2, 3, 4, 5, 6])  
  10. >>> ex2.shape  
  11. (6,)  
Note that ravel() returns a view of a when possible. So modifying ary also modifies ex2. ]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. ary = x[::2]). If you want a copy rather than a view, use:
  1. >>> ex3 = ary.flatten()  
  2. >>> ex3  
  3. array([1, 2, 3, 4, 5, 6])  
  4. >>> ex3.shape  
  5. (6,)  
  6. >>> ary[0,0]=10  
  7. >>> ary  
  8. array([[10,  2,  3],  
  9.        [ 4,  5,  6]])  
  10. >>> ex3  
  11. array([1, 2, 3, 4, 5, 6])  
If you just want an iterator, use np.ndarray.flat:
  1. >>> ex4 = ary.flat  
  2. >>> ex4  
  3. <numpy.flatiter object at 0x2cbfce0>  
  4. >>> list(ex4)  
  5. [10, 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...