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

使用numpy处理缺失值实现不同形状数组的按列拼接

Numpy数组长度不一致按列拼接问题解决

错误原因

你代码报错的核心问题是计算填充行数时错误对形状不匹配的两个数组直接执行减法arr1 - arr,numpy无法对(7,1)和(6,1)维度的数组做广播运算,因此抛出形状不匹配错误。你实际需要的填充行数是新旧数组的行数差值,不需要对数组本身做减法。

修正后的完整代码

import pandas as pd
import numpy as np

df = pd.DataFrame({
'col1': [101, 200, 306, 402, 500, 600],
'col2': [100, 200, 300, 400, 500, 600]})

arr = np.array(df['col1'] - df['col2']).reshape((-1, 1))

df = pd.DataFrame({
'col1': [103, 220, 316, 406, 501, 606, 348],
'col2': [101, 200, 306, 402, 500, 600, 0]})

arr1 = np.array(df['col1'] - df['col2']).reshape((-1, 1))

# 计算需要填充的行数
pad_rows = len(arr1) - len(arr)
# 给原数组末尾补对应行数的0,使两个数组行数一致
arr = np.append(arr, np.zeros((pad_rows, arr.shape[1])), axis=0)
# 按列拼接
arr = np.concatenate((arr, arr1), axis=1)

print(arr)

输出结果

[[  1   2]
 [  0  20]
 [  6  10]
 [  2   4]
 [  0   1]
 [  0   6]
 [  0 348]]

和预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:27:03