[英]I want to add a column in my Data Frame according to some condition
您可以使用pandas 数据框的apply
功能来实现所需的结果。 这是您可能想尝试的代码:
def transform(row):
if row["Price"] == 1500:
scale = 0.15
elif row["Price"] == 800:
scale = 0.10
else:
scale = 0.5
return row["Price"] + row["Price"] * scale
df["RevisedPrice"] = df.apply(transform, axis=1)
当你执行>>>print(df.head())
输出:
Date Event Price RevisedPrice
0 11/8/2011 Music 1500 1725.0
1 11/9/2011 Poetry 800 880.0
2 11/10/2011 Music 1500 1725.0
3 11/11/2011 Comedy 1200 1800.0
4 11/12/2011 Poetry 800 880.0
这是我使用lambda
方法。 您可以通过这种方式应用多个条件。
df['RevisedPrice'] = df['Price'].apply(lambda x: x*1.15 if x == 1500 else (x*1.1 if x == 800 else x*1.05))
输出:
Event Price RevisedPrice
0 music 1500 1725.0
1 poetry 800 880.0
2 music 1500 1725.0
3 comedy 1200 1260.0
4 poetry 800 880.0
PS:我假设else
条件的 RevisedPrice 是x+(x*0.05)
。 如果是x+(x*0.5)
你也可以修改条件。
尝试:
mapping={1500: 1.15, 800: 1.1}
df['RevisedPrice']=df['Price'].map(mapping).fillna(1.5).mul(df['Price'])
所以将所有Price
映射到适当的系数,填充else
(因为.map
映射 1:1,你不能把else
放在那里)。 然后只需将其乘以基列 - Price
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.