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

如何在Python中合并两个CSV文件并实现列方向合并(无需指定列)

Fix: Combine CSV Files Side-by-Side (Column-wise) Instead of Row-wise

Got it, I see the issue here—your current code is stacking the CSV data vertically (adding rows at the bottom) because pd.concat() uses axis=0 by default. To get the side-by-side column merge you want, we just need to adjust a couple of things:

Why Your Current Code Isn't Working

The line pd.concat([pd.read_csv(f) for f in all_filenames ]) defaults to axis=0, which concatenates DataFrames along the row axis. That's why your second CSV's data is showing up at the bottom instead of as a new column next to the first.

The Fix

We need to:

  • Explicitly set axis=1 in pd.concat() to merge horizontally (add columns)
  • Optional but recommended: Specify your two files directly instead of using glob (to avoid unexpected ordering if more CSVs are added to the folder later)

Here's the adjusted code:

import pandas as pd
import os

# Set your working directory
os.chdir("C:/Users/crayx/PycharmProjects/xxx/Csv")

# Read the two CSV files explicitly (replace with your actual filenames)
df1 = pd.read_csv("first_file.csv")  # Contains CustomerID column
df2 = pd.read_csv("second_file.csv") # Contains MiniID column

# Merge horizontally (side-by-side)
combined_csv = pd.concat([df1, df2], axis=1)

# Export to CSV
combined_csv.to_csv("combined_csv.csv", index=False, encoding='utf-8-sig')

Important Notes

  • Row Count Match: Make sure both CSVs have the same number of rows. If they don't, pandas will fill missing values with NaN for the shorter file's extra rows.
  • File Order: Using explicit filenames ensures you don't accidentally merge files in the wrong order (which glob might do if filenames aren't sorted logically).
  • Column Names: Since you don't want to specify columns, this will just append all columns from the second CSV to the first—exactly the side-by-side result you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:24:05