[英]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.