NumPy-扩展并重复 [英] NumPy - Expand and Repeat

查看:164
本文介绍了NumPy-扩展并重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以扩展"数组并重复最后一个元素以填充扩展?

Is there a way to "expand" an array and repeat the last element to fill the expansion?

另一篇帖子讨论了0的扩展和填充但我希望将最后一个值重复作为填充.

Another post talks about expansion and padding with 0 but I wish to repeat the last value as the pad.

说我有一个数组:

[[1, 2],
 [3, 4],
 [0, 0]]

我需要插入[5, 6, 6]来替换[0, 0],显然NumPy不允许这样做.但是我可以重塑/扩展为:

And I need to insert [5, 6, 6] to replace the [0, 0], obviously NumPy wouldnt allow this. But can I reshape/expand to:

[[1, 2, 2],
 [3, 4, 4],
 [5, 6, 6]]

我正在读取一个文件,其中值的数量可能会有所不同,但是我需要数组的形状相同.一种方法是先读取文件并找到最大长度,然后再次读取该文件以填充,但该文件为10GB以上,因此我希望通过扩展"并用重复回填来单次执行. /p>

I'm reading through a file where the number of values may vary in length, but I need the array to be of the same shape. One way to do this is read through the file first and find the maximum length, then read it again an populate, but the file is 10GB+ so I would prefer to do it on a single pass by "expanding" and backfilling with repeats.

推荐答案

看起来您需要的是

Looks like what you require is numpy.pad using the edge mode. From the doc:

‘edge’
    Pads with the edge values of array.

示例代码:

>>> ar = np.array([[1,2], [4,5]])
>>> ar
array([[1, 2],
       [4, 5]])
>>> np.pad(ar, [(0, 0), (0, 4)], mode="edge")
array([[1, 2, 2, 2, 2, 2],
       [4, 5, 5, 5, 5, 5]])

第一个(0,0)元组在第一个轴上未指定填充,而第二个基本上是在左边添加0填充,在右边添加4"

The first (0, 0) tuple specify no padding on the first axis, while the second basically does "add 0 padding to the left and 4 to the right"

这篇关于NumPy-扩展并重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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