Issue
I need help in storing the combinations of column vectors' values in a numpy array.
My problem consists of two column vectors, having size nx1 and mx1, with n=m, and finding n combinations.
I then vertical stacked these column vectors in a matrix, having size nx2.
I found the combinations with the itertools.combination function of python, but I struggle to store them in a numpy array, since itertools gives n rows of tuples.
The main example I found online is reported below:
import itertools
val = [1, 2, 3, 4]
com_set = itertools.combinations(val, 2)
for i in com_set:
print(i)
Output:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
Now, in my case, I have two vectors, val and val1, different from each other.
And, I would need the output in a numpy array, possible a matrix, so I can apply the maximum likelihood estimation method on these values.
Solution
You are looking for itertools.product
instead of itertools.combinations
.
x = [1, 2, 3]
y = [4, 5, 6]
z = list(itertools.product(x, y))
# z = [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
You can turn the result into a (n * n, 2) shaped array by simply passing the result to np.array
:
result = np.array(z)
# array([[1, 4],
# [1, 5],
# [1, 6],
# [2, 4],
# [2, 5],
# [2, 6],
# [3, 4],
# [3, 5],
# [3, 6]])
Finally, you can also do this with numpy directly, albeit in a different order:
result = np.stack(np.meshgrid(x, y)).reshape(2, -1).T
# array([[1, 4],
# [2, 4],
# [3, 4],
# [1, 5],
# [2, 5],
# [3, 5],
# [1, 6],
# [2, 6],
# [3, 6]])
Answered By - Chrysophylaxs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.