栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python如何用零填充numpy数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python如何用零填充numpy数组

很简单,使用参考形状创建一个包含零的数组:

result = np.zeros(b.shape)# actually you can also use result = np.zeros_like(b) # but that also copies the dtype not only the shape

然后在需要的地方插入数组:

result[:a.shape[0],:a.shape[1]] = a

瞧,您已经填充了它:

print(result)array([[ 1.,  1.,  1.,  1.,  1.,  0.],       [ 1.,  1.,  1.,  1.,  1.,  0.],       [ 1.,  1.,  1.,  1.,  1.,  0.],       [ 0.,  0.,  0.,  0.,  0.,  0.]])

如果您定义应该在左上方插入元素的位置,也可以使其更通用

result = np.zeros_like(b)x_offset = 1  # 0 would be what you wantedy_offset = 1  # 0 in your caseresult[x_offset:a.shape[0]+x_offset,y_offset:a.shape[1]+y_offset] = aresultarray([[ 0.,  0.,  0.,  0.,  0.,  0.],       [ 0.,  1.,  1.,  1.,  1.,  1.],       [ 0.,  1.,  1.,  1.,  1.,  1.],       [ 0.,  1.,  1.,  1.,  1.,  1.]])

但请注意,偏移量不要超过允许的范围。例如

x_offset = 2
,这将失败。


如果您有任意数量的维,则可以定义切片列表以插入原始数组。我发现有趣的是可以玩一下,并创建了一个填充函数,该函数可以填充(偏移)任意形状的数组,只要数组和引用的维数相同且偏移量不太大即可。

def pad(array, reference, offsets):    """    array: Array to be padded    reference: Reference array with the desired shape    offsets: list of offsets (number of elements must be equal to the dimension of the array)    """    # Create an array of zeros with the reference shape    result = np.zeros(reference.shape)    # Create a list of slices from offset to offset + shape in each dimension    insertHere = [slice(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]    # Insert the array in the result at the specified offsets    result[insertHere] = a    return result

和一些测试用例:

import numpy as np# 1 Dimensiona = np.ones(2)b = np.ones(5)offset = [3]pad(a, b, offset)# 3 Dimensionsa = np.ones((3,3,3))b = np.ones((5,4,3))offset = [1,0,0]pad(a, b, offset)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661762.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号