【问题标题】:Combine rows to remove duplicates in CSV Python and Pandas合并行以删除 CSV Python 和 Pandas 中的重复项
【发布时间】:2018-10-23 11:44:06
【问题描述】:

我正在尝试使用 python 和 pandas 将多组行组合在一起以删除 CSV 中的重复项。基于一个共同的值,“ID”,如果有重复的行,来自另一列“HostAffected”的值应该与换行符组合。与这篇文章类似:enter link description here 但是我需要保留所有等于相同 ID 的现有值。我已经使用下面的代码作为示例对列进行了类似的操作,但是它并不完全相同:

df = pd.read_csv("output.csv")

cols = ['Host','Protocol','Port']
newcol = ['/'.join(i) for i in zip(df['Host'],df['Protocol'],df['Port'].map(str))]
df = df.assign(HostAffected=newcol).drop(cols, 1)

到目前为止我有这个代码:

df.groupby(['Plugin ID','Description])[HostAffected'].apply(list)

改编自此线程:enter link description here 但是这不起作用。

我的数据集示例如下所示:

PluginID    Description HostAffected
10395   Windows SMB Shares Enumeration  10.0.0.10/tcp/445
10396   Windows SMB Shares Access   10.0.0.10/tcp/445
10396   Windows SMB Shares Access   192.168.0.12/tcp/445
10398   Windows SMB LsaQueryInformationPolicy   10.0.0.10/tcp/445
10399   SMB Use Domain SID to Enumerate Users   10.0.0.10/tcp/445
10400   Windows SMB Registry Remotely Accessible    10.0.0.10/tcp/445
10736   DCE Services Enumeration    10.0.0.10/tcp/139
10736   DCE Services Enumeration    10.0.0.10/tcp/445
10736   DCE Services Enumeration    192.168.0.12/tcp/445

这些值以逗号分隔,但我使用空格使其更清晰。我希望它看起来像这样,其中“插件 ID”和“描述”只有一个唯一行,并且“HostAffected”列合并:

ID  Description HostAffected
10395   Windows SMB Shares Enumeration  10.0.0.10/tcp/445
10396   Windows SMB Shares Access   10.0.0.10/tcp/445
192.168.0.12/tcp/445
10398   Windows SMB LsaQueryInformationPolicy   10.0.0.10/tcp/445
10399   SMB Use Domain SID to Enumerate Users   10.0.0.10/tcp/445
10400   Windows SMB Registry Remotely Accessible    10.0.0.10/tcp/445
10736   DCE Services Enumeration    10.0.0.10/tcp/139
10.0.0.10/tcp/445
192.168.0.12/tcp/445

基本上,多组 HostsAffected 可能有相同的 ID 和描述。任何帮助都将不胜感激,因为这比将列组合在一起稍微复杂和具有挑战性。

【问题讨论】:

  • 你需要df.groupby(['ID','Description'],as_index=False)['HostAffected'].apply(', '.join) 吗?
  • df.groupby(['ID','Description'],as_index=False)['HostAffected'].apply(list) ?
  • 您好我已经尝试了这两项工作,我没有收到错误,只是没有结合。我确实在这个线程中看到了你自己的答案@jezrael 20,我认为它可以工作stackoverflow.com/questions/49625148/… 但没有。
  • 你能解释一下为什么它不起作用吗?
  • @jezrael 输出没有结合每个 Plugin_ID 和描述的 HostAffected 列。事实上,它不会以任何方式影响输出,如果我将行注释掉,我会得到与未注释掉时相同的输出。

标签: python pandas csv dataframe pandas-groupby


【解决方案1】:

在 cmets 之后,如果使用 applyjoin by line break 跟踪 wthitespaces,我们会得到它 strip

df['Description'] = df['Description'].str.strip()

(df.groupby(['Plugin ID','Issue'])['HostAffected']
   .apply('\n'.join)
   .reset_index())

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2019-04-30
    • 2018-01-21
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多