在python中有什么方法可以组合两个不同大小的数组吗?



有两个数组,它们的形状是(5,5)和(3,3)。

(5, 5)
[[5. 5. 5. 5. 5.],
[5. 5. 5. 5. 5.],
[5. 5. 5. 5. 5.],
[5. 5. 5. 5. 5.],
[5. 5. 5. 5. 5.]]
(3, 3)
[[1. 1. 1.],
[1. 1. 1.],
[1. 1. 1.]]

我希望结果是一个5x8的数组,就像下面的

[[5 5 5 5 5 1 1 1],
[5 5 5 5 5 1 1 1],
[5 5 5 5 5 1 1 1],
[5 5 5 5 5 0 0 0],
[5 5 5 5 5 0 0 0]]

您可以创建一个具有最终大小的空数组(如np.zeros(5,8)),然后填充它

不使用for循环,可以将两个数组赋值为空数组

的切片。
final = np.zeros(5,8)
final[:4,:4] = array1 
final[:3,5:] = array2
array_a = [[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]]
array_b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
row_a = 5
column_a = 5
row_b = 3
column_b = 3
final_row = max(row_a, row_b)
final_col = column_a + column_b

def convert_array(array, row, col, target_row, target_col, from_left_to_right=True):
for col_index in range(col, target_col):
for row_index in range(0, row):
if from_left_to_right:
array[row_index].append(0)
else:
array[row_index].insert(0, 0)
for row_index in range(row, target_row):
array.append([])
for col_index in range(0, target_col):
array[row_index].append(0)

# convert array a to an array with the same size of the final array
convert_array(array_a, row_a, column_a, final_row, final_col, from_left_to_right=True)
print array_a
# convert array b to an array with the same size of the final array
convert_array(array_b, row_b, column_b, final_row, final_col, from_left_to_right=False)
print array_b
# merge array
ret = []
for row_index in range(0, final_row):
ret.append([])
for col_index in range(0, final_col):
value = array_a[row_index][col_index] ^ array_b[row_index][col_index]
ret[row_index].append(value)
print ret
[[5, 5, 5, 5, 5, 0, 0, 0], [5, 5, 5, 5, 5, 0, 0, 0], [5, 5, 5, 5, 5, 0, 0, 0], [5, 5, 5, 5, 5, 0, 0, 0], [5, 5, 5, 5, 5, 0, 0, 0]]
[[0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
[[5, 5, 5, 5, 5, 1, 1, 1], [5, 5, 5, 5, 5, 1, 1, 1], [5, 5, 5, 5, 5, 1, 1, 1], [5, 5, 5, 5, 5, 0, 0, 0], [5, 5, 5, 5, 5, 0, 0, 0]]

最新更新