2017年6月24日 星期六

[ Python 常見問題 ] Numpy - Good ways to “expand” a numpy ndarray?

Source From Here
Question
Are there good ways to "expand" a numpy ndarray? Say I have an ndarray like this:
  1. [[1 2]  
  2. [3 4]]  
And I want each row to contains more elements by filling zeros:
  1. [[1 2 0 0 0]  
  2. [3 4 0 0 0]]  
I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements from old smaller arrays), just wondering are there graceful ways to do so. Tried numpy.reshape but didn't work:
  1. import numpy as np  
  2. a = np.array([[12], [34]])  
  3. np.reshape(a, (25))  
With output as:
Numpy complains that: ValueError: total size of new array must be unchanged

How-To
There are the index tricks r_ and c_.
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> z = np.zeros((2, 3), dtype=a.dtype)
>>> np.c_[a, z]
array([[1, 2, 0, 0, 0],
[3, 4, 0, 0, 0]])

If this is performance critical code, you might prefer to use the equivalent np.concatenate rather than the index tricks.
>>> np.concatenate((a,z), axis=1)
array([[1, 2, 0, 0, 0],
[3, 4, 0, 0, 0]])

There are also np.resize and np.ndarray.resize, but they have some limitations (due to the way numpy lays out data in memory) so read the docstring on those ones. You will probably find that simply concatenating is better.

沒有留言:

張貼留言

[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...