[PYTHON] Create an empty array in Numpy to add rows for each loop

I think I'll forget it three months later, so make a note.

I get angry when I try to np.r \ _ on an empty array with numpy.

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

However, I don't think this method is 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.]])

This can be solved with 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.]])

Use this method when adding arrays little by little in a for loop.

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

Recommended Posts

Create an empty array in Numpy to add rows for each loop
Add rows to an empty array with numpy
Create a 2D array by adding a row to the end of an empty array with numpy
Various ways to create an array of numbers from 1 to 10 in Python.
Add totals to rows and columns in pandas
Various ways to extract columns in a NumPy array
Convert NumPy array "ndarray" to lilt in Python [tolist ()]
Create an unprivileged container for NVIDIA GPUs in LXC
How to create an image uploader in Bottle (Python)
How to swap elements in an array in Python, and how to reverse an array.
I want to align the significant figures in the Numpy array
I tried to create an article in Wiki.js with SQLAlchemy
Empty multidimensional array in python
Create a python numpy array
How to set the output resolution for each keyframe in Blender
Create an alias for Route53 to CloudFront with the AWS API
Loop the For statement in reverse in an HTML file on Django
Get an evaluation score for each task in DeepChem's multitask learning
How to create a heatmap with an arbitrary domain in Python
[Note] Items to check when an infinite loop occurs in pyenv
[For Python] Quickly create an upload file to AWS Lambda Layer
Fixed an issue where numpy.memmap wouldn't fit in numpy array memory