【问题标题】:Merge multiple CSV rows into 1 in Python在 Python 中将多个 CSV 行合并为 1
【发布时间】:2020-02-07 22:18:34
【问题描述】:

我有一个包含数百行的 CSV 文件,如下所示!如何合并这两行,只有第二列值更新为 CVE-2017-3006、CVE-2017-3007,其余保持不变

【问题讨论】:

标签: python pandas csv


【解决方案1】:
import pandas as pd

# Create a dummy dataframe like yours
df = pd.DataFrame([
    {"C1": "0", "C2": "A", "C3": "9.0", "C4": "High", "C5": "zaid", "C6": "TCP", "C7": "445", "C8": "some_text", "C9": "some_other_text"},
    {"C1": "0", "C2": "B", "C3": "9.0", "C4": "High", "C5": "zaid", "C6": "TCP", "C7": "445", "C8": "some_text", "C9": "some_other_text"},
    {"C1": "1", "C2": "A", "C3": "17.0", "C4": "High", "C5": "zaid", "C6": "TCP", "C7": "445", "C8": "some_text", "C9": "some_other_text"},
    {"C1": "1", "C2": "B", "C3": "17.0", "C4": "High", "C5": "zaid", "C6": "TCP", "C7": "445", "C8": "some_text", "C9": "some_other_text"},
    {"C1": "1", "C2": "C", "C3": "17.0", "C4": "High", "C5": "zaid", "C6": "TCP", "C7": "445", "C8": "some_text", "C9": "some_other_text"},
])

# Group by all columns you want to keep, and aggregate C2 into a list
grouped = df.groupby(["C1","C3","C4","C5","C6","C7","C8","C9"], as_index=False).agg({
    "C2":lambda x:x.tolist()
})
print(grouped)

      C1    C3    C4    C5   C6   C7         C8               C9         C2
0  0   9.0  High  zaid  TCP  445  some_text  some_other_text     [A, B]
1  1  17.0  High  zaid  TCP  445  some_text  some_other_text  [A, B, C]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 2018-01-11
    • 2021-07-07
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多