Sometimes, we want to use numpy to build an array of all combinations of two arrays with Python.
In this article, we’ll look at how to use numpy to build an array of all combinations of two arrays with Python.
How to use numpy to build an array of all combinations of two arrays with Python?
To use numpy to build an array of all combinations of two arrays with Python, we can use the numpy.meshgrid
method.
For instance, we write
np.stack(np.meshgrid([1, 2, 3], [4, 5], [6, 7]), -1).reshape(-1, 3)
to call meshgrid
with a nested list to return the cartesian product of the nested lists.
Then we reshape the returned array with reshape
into a nested list with 3 items in each list and transposed.
Conclusion
To use numpy to build an array of all combinations of two arrays with Python, we can use the numpy.meshgrid
method.