【问题标题】:Using a dictionary to replace a variable's value使用字典替换变量的值
【发布时间】:2022-01-14 04:01:11
【问题描述】:

在我的数据集中,我有三列:产品、市场和产品类型。对于具有不同产品类型的产品,我必须将 product_type 值替换为以下顺序的值:marketplace = 200、300、400 和 500。输入文件如下所示:

product Marketplace product_type
1                  200            X
2                  300            A
2                  400            A
2                  200            A
3                  500            A
3                  400            A
3                  300            B

这是输出的样子:

  product Marketplace product_type
    1                  200            X
    2                  300            A
    2                  400            A
    2                  200            A
    3                  500            B
    3                  400            B
    3                  300            B

因为我们无法获取市场 == 200 的信息,我们将切换到市场 == 300 并替换我拥有的所有集合的值,产品 == 3。 这是我使用的代码:

mp_correspondence = {200:1, 
                     300:2,
                     400:3,
                     500:4, 
                   }
df['ranking'] = df['marketplace'].map(mp_correspondence)
number_list = set(df['product '])


for i in product_list:
    df_product_frame = df[df['product '] == i].copy()
    nr_rows = df_product_frame['product'].count()
    if nr_rows > 1:
        product_type_count = set(df_product_frame['product_type'])
        print(product_type_count )
        preced_value = set(df['ranking'])
        print(preced_value)
        if product_type_count != 1:
           res = next(iter(preced_value))
           print("The first key of dictionary is:" + str(res))      
    else:
        print('Lesser than 1')

但最重要的是,优先排名列未显示与市场产品类型相关的正确值。有什么方法可以帮助您解决错误并获得替换值的方法?

【问题讨论】:

    标签: python pandas dataframe dictionary replace


    【解决方案1】:

    这个问题对我来说并不清楚,但这会给你预期的输出:

    df['product_type'] = (
        df.assign(ranking=df['Marketplace'].map(mp_correspondence)) \
          .sort_values('ranking').groupby('product')['product_type'].transform('first')
    )
    print(df)
    
    # Output:
       product  Marketplace product_type
    0        1          200            X
    1        2          300            A
    2        2          400            A
    3        2          200            A
    4        3          500            B
    5        3          400            B
    6        3          300            B
    

    【讨论】:

    • 如您所愿吗?
    • 对于 product_type 重复的产品,以按照字典中附加的顺序从市场中获取值。
    最近更新 更多