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

Python/pandas中如何横向拼接(cbind)3个DataFrame得到50行15列结果

问题原因
  • pd.concat默认沿**行方向(axis=0)**拼接,也就是纵向堆叠三个数据集,所以会得到150行的结果,不同子数据集的列自动对齐,不存在的列填充NaN,最终维度为150×15。
  • 三个拆分得到的子DataFrame继承了原始iris数据集的索引:Setosa类对应索引049、Versicolor对应5099、Virginica对应100~149,即使指定沿列拼接,索引不匹配也会产生大量NaN,行数仍然为150。
解决方案

先重置每个子数据集的索引,再指定沿**列方向(axis=1)**拼接即可:

# 重置所有子DataFrame的索引,丢弃原数据集的索引值
df_setosa = df_setosa.reset_index(drop=True)
df_virginica = df_virginica.reset_index(drop=True)
df_versicolor = df_versicolor.reset_index(drop=True)

# 沿列方向横向拼接
concat_df  = pd.concat([df_setosa, df_virginica, df_versicolor], axis=1)

# 验证维度,输出为 (50, 15)
print(concat_df.shape)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:06:03