4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Numpyでループごとに行を追加していくために空の配列を作る

Posted at

多分三ヶ月後に忘れてると思うのでメモ.

numpyで,空の配列にnp.r_しようとすると怒られます.

arr = np.array([])
additional = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.r_[arr, additional]
print(arr)

>>>
ValueError: all the input arrays must have same number of dimensions

とはいえ,↓こんなやり方はPythonicじゃないと思います.

arr = np.zeros([1, 3])
additional = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.r_[arr, additional][1:]
print(arr)

>>>
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

これは,numpy.emptyで解決できます.

arr = np.empty([0, 3])
additional = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.r_[arr, additional]
print(arr)

>>>
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

forループで配列を少しずつ追加していくときもこの方法で.

arr = np.empty([0, 3])
for i in range(3):
  additional = np.ones([1, 3]) * i
  arr = np.r_[arr, additional]
print(arr)

>>>
[[ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 2.  2.  2.]]
4
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?