2017年6月2日 星期五

[ Python 常見問題 ] Numpy - Append a 1d array to a 2d array in Numpy Python

Source From Here
Question
I have a numpy 2D array [[1,2,3]]. I need to append a numpy 1D array,( say [4,5,6]) to it, so that it becomes [[1,2,3], [4,5,6]]. This is easily possible using lists, where you just call append on the 2D list.

But how do you do it in Numpy arrays? np.concatenate and np.append don't work. they convert the array to 1D for some reason.

How-To
You want np.vstack (Stack arrays in sequence vertically as row wise.):
>>> import numpy as np
>>> a = np.array([[1,2,3]])
>>> b = [4,5,6]
>>> np.vstack([a, b])
array([[1, 2, 3],
[4, 5, 6]])

>>> np.vstack([a, [[4,5,6],[7,8,9]]])
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])


沒有留言:

張貼留言

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