2

I want to add another column RevisedPrice based on mentioned condition see the image

if Price=1500 then RevisedPrice=Price+(Price*0.15) else if Price=800 then RevisedPrice=Price+(Price*0.10) else RevisedPrice=Price+(Price*0.5)

Below is my code------------

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']]

i am getting my column value as RevisedPrice=Price+(Price*0.5)

DOOM
  • 1,170
  • 6
  • 20

3 Answers3

2

You can use the apply function of pandas dataframe to achieve the desired result. Here is the code you might want to try:

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)

And when you execute >>>print(df.head())

OUTPUT:

         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
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
1

This is my approach with lambda. You can apply multiple condition with this way.

df['RevisedPrice'] = df['Price'].apply(lambda x: x*1.15 if x == 1500 else (x*1.1 if x == 800 else x*1.05))

Output:

    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: I assume RevisedPrice for else condition is x+(x*0.05). If it is x+(x*0.5) you can modify the condition as well.

talatccan
  • 743
  • 5
  • 19
0

Try:

mapping={1500: 1.15, 800: 1.1}
df['RevisedPrice']=df['Price'].map(mapping).fillna(1.5).mul(df['Price'])

So map all the Price to proper coefficient, fill the else (since .map maps 1:1, you can't put else there). Then just multiply it by the base column - Price

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34