我可以使用np.resize用np.nan填充数组吗 [英] Can I use np.resize to pad an array with np.nan

查看:193
本文介绍了我可以使用np.resize用np.nan填充数组吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们

a = np.array([[1, 2], [3, 4]])
a

array([[1, 2],
       [3, 4]])

然后使用resize

b = np.resize(a, (3, 3))
b

array([[1, 2, 3],
       [4, 1, 2],
       [3, 4, 1]])

现在,

b以不规则的顺序包含了来自a的所有信息.有没有办法利用它来创建左上角看起来像的,但是现在有一个新列和一个新行np.nan?

b now has all of the information from a if in a wonky order. Is there a way to leverage this to create what looks like a in the top left but now has one new column and one new row of np.nan?

c = np.empty(b.shape)
c.fill(np.nan)
c[:a.shape[0], :a.shape[1]] = a
c

array([[  1.,   2.,  nan],
       [  3.,   4.,  nan],
       [ nan,  nan,  nan]])


很显然,上面的代码完成了同样的事情.我只是忍不住想起可以以某种方式使用resize来更有效地完成此任务.


Obviously the above code accomplishes the same thing. I just can't help but think that resize can be used in some way to accomplish this more efficiently.

推荐答案

也许看看 pad :

>>> np.pad(a, ((0,1),(0,1)), 'constant', constant_values=np.nan)
array([[  1.,   2.,  nan],
       [  3.,   4.,  nan],
       [ nan,  nan,  nan]])

请注意,nan实际上是一个浮点数,因此,如果尝试使用整数dtypes进行此操作,请注意.您可能更喜欢使用掩码数组.

Note that nan is actually a float, so take care if trying to do this with integer dtypes. You might prefer to use masked arrays.

这篇关于我可以使用np.resize用np.nan填充数组吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆