如何在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=1inpd.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
NaNfor the shorter file's extra rows. - File Order: Using explicit filenames ensures you don't accidentally merge files in the wrong order (which
globmight 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
相关产品推荐
相关产品推荐

