【问题标题】:How to replace informations in a dataFrame using Pandas and Python?如何使用 Pandas 和 Python 替换数据框中的信息?
【发布时间】:2021-08-11 14:40:51
【问题描述】:

我需要一些帮助:

如何使用 Pandas 和 Python 更新文件 file_csv_reference.csv dataFrame 的列?

file_csv_reference.csv

cod_example
123456
123456
123456
789101
789101
121314
121314

有重复信息的行,我想用下面文件中相应的更新代码替换它们:

file_with_updated_cod.csv

old_cod   updated_cod
123456      ;1234567
789101      ;7891011
121314      ;1213141

到目前为止,我一直在考虑这种方式(但我无法正确运行):

import pandas as pd
file01 = pd.read_csv("file_csv_reference.csv", encoding = "utf-8", delimiter = ";", header = 0)
file02 = pd.read_csv("file_with_updated_cod.csv", encoding = "utf-8", delimiter = ";", header = 0)
for oldcod in file01['cod_example']:
    for cod in file02['old_cod']:
       if oldcod == cod:
       #in this part I would like to replace the data in the file01 column cod_example
       # with file01['updated_cod'] in the respective column

你能帮我解决这个问题吗?谢谢!

【问题讨论】:

    标签: python pandas dataframe csv


    【解决方案1】:

    你可以使用.map:

    df1 = pd.read_csv("file_csv_reference.csv")
    df2 = pd.read_csv("file_with_updated_cod.csv", sep=";")
    
    df1["cod_example"] = df1["cod_example"].map(
        df2.set_index("old_cod")["updated_cod"]
    )
    print(df1)
    

    打印:

       cod_example
    0      1234567
    1      1234567
    2      1234567
    3      7891011
    4      7891011
    5      1213141
    6      1213141
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2018-03-12
      • 2022-01-26
      • 2012-08-26
      • 2017-02-28
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多