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

如何用Python和Pandas将CSV中三列合并为一列并删除原列

解决CSV列合并与原列删除问题

Hey there! Let's get your CSV processing working correctly. I see a couple of small issues in your current code that are keeping it from producing the output you want, plus we can simplify the CSV merging step using pandas directly (which is more reliable than manual file reading/writing).

问题分析

  1. 手动合并CSV的潜在问题: 你用文件读写的方式合并CSV,可能会遇到编码不一致、换行符问题,而且pandas本身就有更简洁的批量合并方法。
  2. 列合并的类型问题: Port列大概率是整数类型,直接和字符串拼接会报错,需要先转换成字符串。
  3. 未删除原列: 你的代码没有移除Host、Protocol、Port这三列。
  4. 列名不一致: 你的目标列名是HostsAffected(带s),但代码里写的是HostAffected。

修正后的完整代码

import pandas as pd
import glob

# 1. 批量读取所有CSV文件并合并成一个DataFrame
interesting_files = glob.glob("*.csv")
df_list = []
for file in interesting_files:
    df = pd.read_csv(file)
    df_list.append(df)
combined_df = pd.concat(df_list, ignore_index=True)

# 2. 合并Host、Protocol、Port为HostsAffected列
# 先把Port转成字符串,避免类型错误
combined_df['HostsAffected'] = combined_df['Host'] + "/" + combined_df['Protocol'] + "/" + combined_df['Port'].astype(str)

# 3. 删除原来的三列
combined_df = combined_df.drop(columns=['Host', 'Protocol', 'Port'])

# 4. 保存结果到新文件
combined_df.to_csv("newoutput.csv", index=False)

代码解释

  • 批量合并CSV: 用pd.concat把所有读取的DataFrame合并成一个,ignore_index=True会重置行索引,避免重复索引问题。
  • 列合并处理: 用astype(str)把Port列转换成字符串,确保拼接时不会因为类型不匹配报错。
  • 删除原列: drop(columns=...)可以直接移除指定的列,同时保留CSV里的其他列。
  • 保存文件: index=False避免把pandas的行索引写入CSV文件,让输出格式更干净。

验证输出

运行这段代码后,你的newoutput.csv会保留原来的其他列,同时只保留合并后的HostsAffected列,格式和你期望的一致:

HostsAffected,其他列名
10.0.0.10/tcp/445,其他列值
10.0.0.10/tcp/49707,其他列值
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:26:58