我正在尝试使用def

时间:2019-01-19 20:19:39

标签: python python-3.x pandas

该代码应该根据性别的值进行条件附加,但是添加未正确执行

# Using apply on Male and Female
# Still didnt get the expected result to do addition and sub to the male and female


raw_data = {'Gender_demo': ["Male", "Female", "Male", "Female"],'Price': [100, 200, 300, 400]}
df = pd.DataFrame(raw_data, columns = ['Gender_demo','Price'])

df

def gensub (x, y, z):
    if y == z:
        return x + 75
    else:
        return x


df["Gender_Discount"]=df.Price.apply(gensub, y ="f.Gender_demo", z="Male")

df.head()

我有什么

  Gender_demo  Price  Gender_Discount
0        Male    100              100
1      Female    200              200
2        Male    300              300
3      Female    400              400

如果性别是男性,我期望在最后的Gender_Discount变量中增加75。

1 个答案:

答案 0 :(得分:0)

不需要自定义功能

df['Discount']=df.Price.add(df.Gender_demo.eq('Male')*75,fill_value=0)
df
  Gender_demo  Price  Discount
0        Male    100       175
1      Female    200       200
2        Male    300       375
3      Female    400       400