【问题标题】:Merge Update and Remove Multiple values in a csv file using python使用python合并更新和删除csv文件中的多个值
【发布时间】:2020-07-25 14:10:00
【问题描述】:

如果 ID 列匹配,我需要将两个 .csv 文件合并到包含更新值的第三个文件中。 当两个文件中存在同一行时,应使用第二个 csv 文件。每个文件的第一列都包含一个 ID。 CSV table

csv1=pd.read_csv("csv1.csv")
csv2=pd.read_csv("csv2.csv")

csv1.update(csv2)
csv_temp = pd.concat([csv1, csv2]).drop_duplicates(subset=['Product ID', 'Product', 'Product Colour']).reset_index(drop=True)
csv3 = csv_temp.drop_duplicates(subset=['Product ID', 'Product', 'Product Colour']).reset_index(drop=True)

csv3.to_csv("csv3.csv", index=False)

我正在使用 python3 和 panda 库

【问题讨论】:

    标签: python python-3.x pandas numpy csv


    【解决方案1】:

    在使用 read_csv 函数(read_csv doc) 的 index_col 参数读取 CSV 文件时,您应该将两个数据框 index 设置为产品 ID。 这很重要,因为更新函数将使用它来匹配第二个文件中的行。

    您的示例使用行号作为索引,如果要更新的产品位于第二个 csv 的另一行中,它将不起作用。

    这是我用来测试的示例代码:

    index1 = ['AAA', 'BBB', 'CCC', 'EEE']
    col11 = ['Apple', 'Banana', 'Orange', 'EEE']
    col21 = ['green', 'yellow', 'red', 'EEE']
    
    index2 = ['AAA', 'BBB', 'CCC', 'FFF']
    col12 = ['Kiwi', 'Banana', 'Orange', 'FFF']
    col22 = ['green', 'yellow', 'orange', 'FFF']
    
    df1 = pd.DataFrame(list(zip(col11, col21)), index=index1)
    df2 = pd.DataFrame(list(zip(col12, col22)), index=index2)
    
    # Update first df using values in the second one
    df1.update(df2)
    # Merging the two df for rows only in one file and not the other one
    df3 = pd.concat([df1,df2]).drop_duplicates()
    

    然后我得到:

    AAA    Kiwi   green
    BBB  Banana  yellow
    CCC  Orange  orange
    EEE     EEE     EEE
    FFF     FFF     FFF
    

    AAA 和 CCC 产品都在 df 中并已正确更新。 EEE产品仅在第一个,FFF产品仅在第二个;他们都在结果df中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2018-06-11
      • 2017-01-03
      相关资源
      最近更新 更多