Python比较和更新CSV-Fi

2024-04-25 02:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个CSV文件。你知道吗

csv\u 1列:

AP Name       Mac           Switch      Port
AP-2-2    001122334455   switchname1    0/37
AP-2-3    554433221100   switchname2    0/41

csv 2列:

    Mac         Switch      Port
001122334455   switchname1  0/37
554433221100   switchname2  0/41

我想根据找到mac地址匹配的时间,用csv_2中的交换机和端口更新csv_1中的交换机和端口列(它们不是按顺序排列的)。你知道吗

在python中正确地完成这一任务的最佳和最有效的方法是什么?我知道如何读取CSV文件,只是不知道如何正确地检查值。你知道吗


Tags: 文件csv端口nameportmac地址时间
2条回答

因为您没有提供具体的代码示例,所以我假设您已经解析了csv文件,并希望获得处理方面的帮助。尝试以下操作:

for index_2, row_2 in enumerate(csv_2):
    for index_1, row_1 in enumerate(csv_1):
        if row_2.mac == row_1.mac:
            csv_1[index_1].switch = csv_2[index_2].switch
            csv_1[index_1].port = csv_2[index_2].port

然后,将csv\u 1写回文件。你知道吗

您可以使用pandas加入新值:

import pandas as pd

df1 = pd.read_csv("<path to csv1>.csv")
df2 = pd.read_csv("<path to csv2>.csv").rename(columns={"Switch": "new_switch", "Port": "new_port"})

# clean up column names
df1.columns = [i.strip() for i in df1.columns]
df2.columns = [i.strip() for i in df2.columns]

# join in new values
result = df1.join(df2.set_index("Mac"), on="Mac")

# use the new values where they're defined, otherwise fill in with the old values
result["Switch"] = result["new_switch"].fillna(result["Switch"])
result["Port"] = result["new_port"].fillna(result["Port"])

# delete the "new" columns, which are no longer needed
del result["new_switch"], result["new_port"]

# write out
result.to_csv("<path to new csv>.csv", index=False)

这假设您的csv2对于每个Mac值只有一行。你知道吗

相关问题 更多 >