Proper way to create array/list of arrays from arrays/lists of elements in python
Question:
Suppose I have numpy arrays or lists a
and b
with the same lengths, e.g. a = numpy.array([1,2,3]), b = numpy.array([4,5,6])
and I want to create a numpy.array or list of pairs of the form numpy.array([a[i],b[i]])
. The following code in principle works:
P = [numpy.array([a[i],b[i]]) for i in range(len(a))]
However, I suspect that there is a more elegant way to do it. Moreover, the above code does not work in case a
and b
are scalars, rather than arrays. Ideally, I would like the code to be able to handle both cases. Any suggestions?
Answers:
Assuming, numpy arrays:
P = list(np.c_[a, b])
Or:
P = list(np.vstack([a, b]).T)
Output:
[array([1, 4]), array([2, 5]), array([3, 6])]
NB. It’s generally not a good idea to have lists of arrays, better keep the stacked array.
np.c_[a, b]
array([[1, 4],
[2, 5],
[3, 6]])
Reproducible input:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
Suppose I have numpy arrays or lists a
and b
with the same lengths, e.g. a = numpy.array([1,2,3]), b = numpy.array([4,5,6])
and I want to create a numpy.array or list of pairs of the form numpy.array([a[i],b[i]])
. The following code in principle works:
P = [numpy.array([a[i],b[i]]) for i in range(len(a))]
However, I suspect that there is a more elegant way to do it. Moreover, the above code does not work in case a
and b
are scalars, rather than arrays. Ideally, I would like the code to be able to handle both cases. Any suggestions?
Assuming, numpy arrays:
P = list(np.c_[a, b])
Or:
P = list(np.vstack([a, b]).T)
Output:
[array([1, 4]), array([2, 5]), array([3, 6])]
NB. It’s generally not a good idea to have lists of arrays, better keep the stacked array.
np.c_[a, b]
array([[1, 4],
[2, 5],
[3, 6]])
Reproducible input:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])