python - python:在Numpy数组数组中的每个数组末尾填充零
问题描述
我有一个 Numpy 数组数组,主数组中的每个数组都有不同的大小。我需要在每个数组的末尾用 0 填充,以便主数组内的所有数组长度相等,但我不知道最大长度。我希望它以更简洁的方式完成,而不是在需要时找到最大长度并在末尾分配 0。下面的a已经是一个Numpy aray
a=[
[1,2,3,4],
[3,56],
[8,4,8,4,9,33,55]
] .
In this case maxlength is 7(the length of third array) .
I want final array to look like follows
a=[
[1,2,3,4,0,0,0],
[3,56,0,0,0,0,0],
[8,4,8,4,9,33,55]
]
解决方案
对于 numpy.pad 解决方案,我认为我们需要确保您的输入与您的输入完全一致,以便我们能够获得正确的解决方案。那么它将是:
a=[
np.asarray([1,2,3,4]),
np.asarray([3,56]),
np.asarray([8,4,8,4,9,33,55])
]
max_len = max([len(x) for x in a])
output = [np.pad(x, (0, max_len - len(x)), 'constant') for x in a]
print(output)
>>> [
array([1, 2, 3, 4, 0, 0, 0]),
array([ 3, 56, 0, 0, 0, 0, 0]),
array([ 8, 4, 8, 4, 9, 33, 55])
]
推荐阅读
- twitter-bootstrap - 表单输入中的弹出窗口
- sql-server - 如何在 MSSQL Server 插入或更新触发器上获取行 ID
- java - 在 Control SWT 中适合背景图像
- material-components - 如何使 TextInputLayout 的提示文本垂直居中?
- asp.net - Angular2 显示 .NET API 验证消息
- java - paintComponent 方法只被调用一次
- c# - 根据另一个值有条件地映射 LINQ 中的新属性
- d3.js - Crossfilter 和 DC.js 的平均值
- wpf - 我可以在 WPF 应用程序中使用 ResourceDictionary 和 UserControl 吗
- vba - excel vba 不遵循保存路径并保存在我的文档中