【问题标题】:I am trying to do a conditional addition to the dataframe on gender=male and gender=female using a def [duplicate]我正在尝试使用 def [重复] 对性别 = 男性和性别 = 女性的数据框进行有条件的添加
【发布时间】:2019-01-20 04:23:37
【问题描述】:

代码应该根据性别的值做一个有条件的附加,但是这个附加没有正确执行

# 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。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    不需要自定义函数

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多