numpy 如何通过将第一个元素与第二个元素组合来创建一个新数组?

kmbjn2e3  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(116)

需要一个快速的解决方案在Numpy中获得一个数组在C.数组中的元素的尺寸和数量是不同的。

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

字符串

e1xvtsh3

e1xvtsh31#

# 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)

字符串
使用generator可以接受吗?如果可以,也许这样的东西可以工作:

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)

ldioqlga

ldioqlga2#

import numpy as np

ai,bi = np.mgrid[0:A.shape[0],0:B.shape[0]].reshape(2,-1)
np.c_[A[ai], B[bi]]
array([['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']], dtype='<U11')

字符串
您也可以从itertools使用product

from itertools import product

np.r_[[np.r_[i] for i in product(A, B)]]
array([['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']], dtype='<U11')


您的数据:

A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([['a', 'b'], ['c', 'd'], ['e', 'f']])

相关问题