如何用Python将三个CSV文件合并为单列IP列表格式的CSV?
解决方案
你当前用pd.concat(..., axis=1)是横向拼接,所以三个文件的内容会变成并列的列,这和你要的单列格式不符。需要改成纵向拼接,同时在每个分类的IP数据前插入分类标题行,具体实现如下:
修改后的代码
import pandas as pd # 定义工具函数,生成带分类标题的单列数据块 def create_section(df, section_title): # 创建仅包含分类标题的行(列名统一为"IP") title_row = pd.DataFrame({"IP": [section_title]}) # 将原文件的列重命名为"IP",确保和标题行列名一致 ip_list = df.rename(columns={df.columns[0]: "IP"}) # 拼接标题行和IP数据 return pd.concat([title_row, ip_list], ignore_index=True) # 为每个分类生成对应的数据块 printers_section = create_section(printersFile, "Printers") network_devices_section = create_section(netDevFile, "Network Devices") other_section = create_section(otherFile, "Other") # 纵向拼接所有数据块(axis=0是默认值,可省略) combinedFile = pd.concat([printers_section, network_devices_section, other_section], ignore_index=True) # 导出CSV,注意不要包含表头(已手动插入分类标题) combinedFileName = hospitalName + "Exclude" combinedFile.to_csv(combinedFileName + ".csv", index=False, header=False) print("Check to see if the new files exist!")
关键说明
- 横向转纵向:把
axis=1改成默认的axis=0(纵向拼接),确保所有内容都在同一列。 - 插入分类标题:通过
create_section函数,为每个分类的IP列表前添加一行分类名称,匹配你需要的输出格式。 - 统一列名:将所有数据的列名统一为"IP",避免拼接时出现列名不匹配的问题。
- 取消表头导出:导出时设置
header=False,因为分类名称已作为内容行插入,无需额外表头。
如果你的原始CSV文件结构特殊(比如包含多列需要提取IP),可以补充细节再调整代码。
内容的提问来源于stack exchange,提问作者award19
相关产品推荐
相关产品推荐

