簡體   English   中英

我想根據某些條件在我的數據框中添加一列

[英]I want to add a column in my Data Frame according to some condition

我想根據提到的條件添加另一列 RevisedPrice 看圖片

如果價格=1500 那么修正價格=價格+(價格*0.15) 否則如果價格=800 那么修正價格=價格+(價格*0.10) 否則修正價格=價格+(價格*0.5)

下面是我的代碼------------

df['RevisedPrice']=[x+(0.15*x) if x==1500 else x+(0.10*x) if x==800 else x+(0.05*x) for x in df['Price']]

我將我的列值設為RevisedPrice=Price+(Price*0.5)

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM