如何使用numpy将向量填充和/或截断为指定长度? [英] How can I pad and/or truncate a vector to a specified length using numpy?

查看:663
本文介绍了如何使用numpy将向量填充和/或截断为指定长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个列表:

a = [1,2,3]
b = [1,2,3,4,5,6]

长度可变.

我想返回一个长度为5的向量,这样,如果输入列表的长度为< 5,则将在右边用零填充,如果> 5,则将在第5个元素处将其截断.

I want to return a vector of length five, such that if the input list length is < 5 then it will be padded with zeros on the right, and if it is > 5, then it will be truncated at the 5th element.

例如,输入a将返回np.array([1,2,3,0,0]),输入b将返回np.array([1,2,3,4,5]).

For example, input a would return np.array([1,2,3,0,0]), and input b would return np.array([1,2,3,4,5]).

我觉得我应该能够使用 ,但我似乎无法遵循文档.

I feel like I ought to be able to use np.pad, but I can't seem to follow the documentation.

推荐答案

我不确定这是慢还是快,但是它可以满足您的目的.

This might be slow or fast, I am not sure, however it works for your purpose.

In [22]: pad = lambda a,i : a[0:i] if len(a) > i else a + [0] * (i-len(a))

In [23]: pad([1,2,3], 5)
Out[23]: [1, 2, 3, 0, 0]

In [24]: pad([1,2,3,4,5,6,7], 5)
Out[24]: [1, 2, 3, 4, 5]

这篇关于如何使用numpy将向量填充和/或截断为指定长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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