Nem*_*vic 4 python numpy python-3.x
假设有两个数组:
inner_array = np.array([[3, 3, 3],
[6, 6, 6],
[9, 9, 9]])
outer_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
Run Code Online (Sandbox Code Playgroud)
创建看起来像这样的数组的最干净的方法是什么:
[[ 1, 2, 3, 4, 5],
[16, 3, 3, 3, 6],
[15, 6, 6, 6, 7],
[14, 9, 9, 9, 8],
[13, 12, 11, 10, 9]]
Run Code Online (Sandbox Code Playgroud)
如果能控制外层数组的起始位置就更好了
这是选择起始位置作为附加参数的一种方法 -
def fill_around(inner_array, outer_array, origin=0):
outer_array = np.roll(outer_array, origin)
m,n = inner_array.shape
out = np.pad(inner_array,(1,1))
s = np.split(outer_array, np.cumsum([n+2,m,n+2]))
out[[0,-1]] = [s[0],s[2][::-1]]
out[1:-1,::n+1] = np.dstack([s[3][::-1],s[1]])
return out
Run Code Online (Sandbox Code Playgroud)
给定数据的样本运行 -
In [181]: fill_around(inner_array, outer_array)
Out[181]:
array([[ 1, 2, 3, 4, 5],
[16, 3, 3, 3, 6],
[15, 6, 6, 6, 7],
[14, 9, 9, 9, 8],
[13, 12, 11, 10, 9]])
Run Code Online (Sandbox Code Playgroud)
设置起始位置 -
In [8]: fill_around(inner_array, outer_array, origin=2)
Out[8]:
array([[15, 16, 1, 2, 3],
[14, 3, 3, 3, 4],
[13, 6, 6, 6, 5],
[12, 9, 9, 9, 6],
[11, 10, 9, 8, 7]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |