You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需零填充垂直堆叠不同尺寸的一维NumPy数组生成二维数组

Solution: Vertically Stack Unequal-Length 1D NumPy Arrays Without Zero-Padding

Got it, let's tackle this problem clearly. You want to stack two 1D arrays (like a = np.arange(52) and b = np.arange(62)) into a 2D array, where the shorter array repeats itself to match the length of the longer one—no zero-padding allowed. Here's how to do it:

Step-by-Step Implementation

First, we'll use NumPy's resize function to extend the shorter array by repeating its elements, then vertically stack the two now equal-length arrays.

import numpy as np

# Define your input arrays
a = np.arange(52)  # Length 52
b = np.arange(62)  # Length 62

# Get the lengths of both arrays
len_a, len_b = len(a), len(b)

# Determine the target length (the longer of the two)
max_length = max(len_a, len_b)

# Resize the shorter array to match max_length by repeating its elements
a_resized = np.resize(a, max_length)
# The longer array stays unchanged since its length already matches the target
b_resized = np.resize(b, max_length)

# Vertically stack the two resized arrays into a 2D array
c = np.vstack([a_resized, b_resized])

What This Does

  • np.resize() automatically repeats the array's elements to fill the target length. For a (length 52), resizing to 62 will take the full 52 elements, then add the first 10 elements of a again to reach 62 total.
  • np.vstack() now works because both input arrays are the same length—they get stacked as rows in the resulting 2D array.

Why Your Previous Methods Didn't Work

  • hstack/vstack: These require all input arrays to have matching dimensions (for 1D arrays, that means identical lengths). Your original arrays had different lengths, so they threw errors.
  • np.append/np.concatenate: By default, these concatenate elements along the existing axis (for 1D arrays, that makes a single longer 1D array), not a 2D stacked structure.

Verify the Result

If you print c, you'll see the first row is a repeated enough times to reach 62 elements, and the second row is the full b array—exactly the structure you wanted, with no zero-padding interfering.


内容的提问来源于stack exchange,提问作者Arif zafar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:12:47