我有一个 (4,5) 形状的二维数组和另一个 (4,2) 形状的二维数组。第二个数组包含我需要从第一个数组中过滤掉的开始和结束索引,即我想使用第二个数组对第一个数组进行切片。
np.random.seed(0)
a = np.random.randint(0,999,(4,5))
a
array([[684, 559, 629, 192, 835],
[763, 707, 359, 9, 723],
[277, 754, 804, 599, 70],
[472, 600, 396, 314, 705]])
idx = np.array([[2,4],
[0,3],
[2,3],
[1,3]
])
预期输出 - 可以是以下两种格式之一。用零填充的唯一原因是不支持可变长度二维数组。
[[629, 192, 835, 0, 0],
[763, 707, 359, 9, 0],
[804, 599, 0, 0, 0],
[600, 396, 314, 0, 0]
]
[[0, 0, 629, 192, 835],
[763, 707, 359, 9, 0],
[0, 0, 804, 599, 0],
[0, 600, 396, 314, 0]
]
import numpy as np
# Input arrays
np.random.seed(0)
a = np.random.randint(0, 999, (4, 5))
idx = np.array([[2, 4],
[0, 3],
[2, 3],
[1, 3]])
# Prepare the output array with zeros
output_padded_start = np.zeros_like(a)
output_padded_end = np.zeros_like(a)
# Slice and place the values
for i in range(a.shape[0]):
start, end = idx[i]
sliced_values = a[i, start:end + 1]
output_padded_start[i, :len(sliced_values)] = sliced_values # Padding with zeros at the end
output_padded_end[i, -len(sliced_values):] = sliced_values # Padding with zeros at the start
print("Padded at the end:")
print(output_padded_start)
print("\nPadded at the start:")
print(output_padded_end)
# Output
Padded at the end:
[[629 192 835 0 0]
[763 707 359 9 0]
[804 599 0 0 0]
[600 396 314 0 0]]
Padded at the start:
[[ 0 0 629 192 835]
[763 707 359 9 0]
[ 0 0 804 599 0]
[ 0 600 396 314 0]]