在Jupyter Notebook/Python中用Pandas合并两个.csv文件
解决方法
因为两个CSV结构完全不同,用DataFrame的merge/append确实不合适,直接操作文件内容或者将DataFrame转为字符串拼接是更直接的方案:
方法一:直接读写文件内容(无需pandas)
这种方式最简单,直接读取两个文件的所有内容,拼接后写入新文件:
# 读取第一个CSV的全部内容 with open('csv1.csv', 'r', encoding='utf-8') as f1: csv1_content = f1.read() # 读取第二个CSV的全部内容 with open('csv2.csv', 'r', encoding='utf-8') as f2: csv2_content = f2.read() # 拼接内容(加换行避免两行粘连),写入新文件 with open('combined.csv', 'w', encoding='utf-8') as f_out: f_out.write(csv1_content + '\n' + csv2_content)
如果需要在两部分之间加分隔标识(比如空行或注释),可以修改拼接逻辑:
# 中间加空行和分隔注释 combined_content = f"{csv1_content}\n\n# 以下是实际数据\n\n{csv2_content}"
方法二:用pandas辅助拼接(适合已读取DataFrame的场景)
如果你已经用pandas读取了两个文件,也可以将DataFrame转为CSV格式的字符串后拼接:
import pandas as pd # 读取已完成,直接用你的df1、df2 df1 = pd.read_csv('csv1.csv') df2 = pd.read_csv('csv2.csv') # 转为带表头的CSV字符串(index=False去掉索引列) df1_csv_str = df1.to_csv(index=False) df2_csv_str = df2.to_csv(index=False) # 拼接后写入文件 with open('combined_pandas.csv', 'w', encoding='utf-8') as f_out: f_out.write(df1_csv_str + '\n' + df2_csv_str)
注意事项
- 若CSV包含中文,务必指定正确的编码(如
gbk或utf-8-sig),避免乱码 - 如果第二个CSV的表头和第一个完全无关,直接拼接即可,生成的文件会保留各自的表头和数据行
内容的提问来源于stack exchange,提问作者ClamCoding
相关产品推荐
相关产品推荐

