【问题标题】:Change string values with new values contain in another data frame用新值更改字符串值包含在另一个数据框中
【发布时间】:2022-01-06 17:38:38
【问题描述】:

我有一个包含数千行销售数据的 csv,如下所示:

pd.DataFrame({
    'Item_name': ['guacamole', 'morita', 'verde', 'pico', 'tomatillo'],
    'Inv_number': ['0001', '0002', '0003', '0004', '0005'],
    'Store_name': ['alex', 'pusateris', 'wholefoods','longos', 'metro']

现在项目名称已更改为:

pd.DataFrame ({
'Item_name': ['Dip guacamole', 'morita Spicy', ' Salsa verde', 'Pico de Gallo', 'Roasted tomatillo']

我想要实现的是将旧名称更改为新名称。我对每个项目都使用了以下代码,但这需要很长时间!

sales_df['item_code']= sales_df['item_code'].replace({'Guacamole':'Dip Guacamole'}) 

有没有办法简化这段代码?也许用新名称创建一个列表并遍历销售数据?

期待听到您的 cmets。

谢谢!

【问题讨论】:

    标签: python pandas data-analysis


    【解决方案1】:

    这里使用模糊逻辑。

    # Python env: pip install thefuzz
    # Anaconda env: conda install thefuzz
    
    from thefuzz import process
    
    THRESHOLD = 90  # reject all values below this score (%)
    
    # df: your original dataframe
    # df1: your new names
    df['Item_name_new'] = \
        df['Item_name'].apply(lambda x: process.extractOne(x, df1['Item_name'],
                                  score_cutoff=THRESHOLD)).str[0]
    print(df)
    
    # Output
       Item_name Inv_number  Store_name      Item_name_new
    0  guacamole       0001        alex      Dip guacamole
    1     morita       0002   pusateris       morita Spicy
    2      verde       0003  wholefoods        Salsa verde
    3       pico       0004      longos      Pico de Gallo
    4  tomatillo       0005       metro  Roasted tomatillo
    5      water       0006      nature               None
    

    【讨论】:

    • 我正在尝试使用此解决方案,但出现错误 -----name 'THRESHOLD' is not defined
    • @CarolinaMedina。真对不起。我解决了这个问题。
    • 非常感谢!我不得不在阈值百分比附近玩你,但效果很好。
    【解决方案2】:

    你可以使用replace函数:

    dic = {'Guacamole':'Dip Guacamole', 'morita': 'morita Spicy'}
    sales_df = sales_df.replace({"item_code": dic})
    

    【讨论】:

      【解决方案3】:

      如果库存编号保持不变,则应将其用作索引。 我会尝试在索引和名称之间创建一个映射并将其应用于旧表:

      name_dict = new_df.set_index("Inv_number")["Item_name'"].drop_duplicates()
      old_df["new_names"] = old_df["Inv_number"].map(name_dict)
      

      【讨论】:

        猜你喜欢
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        相关资源
        最近更新 更多