Issue
Need a quick solution in Numpy to get an array in C. The dimensions and number of elements in the arrays are different.
A = [ [1, 2 , 3],
[4, 5, 6],
... ]
B = [ [a, b],
[c, d],
[e, f],
... ]
C = [ [1, 2, 3, a, b],
[1, 2, 3, c, d],
[1, 2, 3, e, f],
[4, 5, 6, a, b],
[4, 5, 6, c, d],
[4, 5, 6, e, f],
... ]
Solution
# Example arrays A and B
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([['a', 'b'], ['c', 'd'], ['e', 'f']])
# Repeat each row of A for the number of rows in B
repeated_A = np.repeat(A, B.shape[0], axis=0)
# Tile B for the number of times A has rows
tiled_B = np.tile(B, (A.shape[0], 1))
# Combine repeated_A and tiled_B along the second axis
C = np.hstack((repeated_A, tiled_B))
print(C)
Is it acceptable to use generator
? If it is, maybe something like this will work:
rows_A, cols_A = A.shape
rows_B, cols_B = B.shape
def generate_rows():
for i in range(rows_A):
for j in range(rows_B):
yield np.concatenate((A[i], B[j]))
C = np.fromiter(generate_rows(), dtype=object, count=rows_A * rows_B)
Answered By - Milos Stojanovic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.