根据字典中的条件创建新列

问题描述 投票:0回答:0

这个问题来自我的工作。我想在基于字典的数据框中创建一个新列“referral_fee”。 我有如下字典:

referral_fees = {
    "Amazon Device Accessories": 0.45,
    "Appliances - Compact": lambda price: 0.15 if 0 < price <= 300 else 
     0.08,
    "Appliances - Full-size": 0.08,
    "Automotive and Powersports": 0.12,
    "Base Equipment Power Tools": 0.12,
    "Baby Products": lambda price: 0.08 if 0 < price <= 10 else 0.15}

如果产品是“Appliances - Compact”,价格有两个条件,如上。数据框中有“价格”列和“类别”列。 Data frame部分如下: ''' |阿辛|类别 |价格 |------------|--------------------------------|---- ------
| 1 |家电-紧凑| 250 | 2 |家电-紧凑| 400 | 3 |汽车和动力运动 | 500 | 4 |婴儿用品 | 9 | 5 |婴儿用品 | 12 | 6 |家电 - 全尺寸 | 275 '''

任何帮助表示赞赏。提前致谢!

预期结果是: ''' |ASIN |类别 |价格 |referral_fee |--------|------------------------------------|---- ------|------------
| 1 |电器 - 紧凑型 | 250 | 0.15 | 2 |电器-紧凑型| 400 | 0.08 | 3 |汽车和动力运动| 500 | 0.12 | 4 |婴儿用品| 9 | 0.08 | 5 |婴儿用品| 12 | 0.15 | 6 |家电-全尺寸| 275 | 0.08 '''

我试过这个:df["referral_fee"] = df["category"].map(referral_fees)

我试过的另一个代码块是:

def referral_col(df):
    mask = df["category"].isin(referral_fees.keys())
    df.loc[mask, "referral_fee"] = df.loc[mask, "unit_sales_price"].apply(
    lambda price: referral_fees[df.loc[mask, "category"]](price))
    return df

第一个代码是给专栏但像这样: 推荐费

<function <lambda> at 0x000001EAFE8CE040>
<function <lambda> at 0x000001EAFE8CE040>
<function <lambda> at 0x000001EAFE8CE040> 

如果我在函数 referral_col 中输入 df,第二个代码块会给我错误,它是: 不可散列的类型:'系列'

python function dictionary calculated-columns
© www.soinside.com 2019 - 2024. All rights reserved.