using pandas apply lambda with conditions

Question:

Product Price Timestamp AdjPrice
A1 1142 1/3/2022
A1 1148 1/4/2022
A1 1177 1/5/2022
A1 1163 1/6/2022
A1 1160 1/7/2022

I have the above dataframe. The last column (AdjPrice) must be populated by multiplying the Price with a static factor (0.15 for instance), if the Timestamp is less than a given date (1/5/2022).

mydate = pd.to_datetime("1/5/2022",format='%d/%m/%Y')

df['AdjPrice'] = df['AdjPrice'].apply(lambda x: (df['Price'] * 0.15) if x['Timestamp'] < mydate else df['Price']

gives me the following error.

TypeError: string indices must be integers

I’m not sure how to achieve this. Help?

Asked By: GMT

||

Answers:

This code will fix your problem:

mydate = pd.to_datetime("1/5/2022",format='%d/%m/%Y')
df['AdjPrice'] = df.apply(lambda x: x['Price'] * 0.15 if pd.to_datetime(x['Timestamp']) < mydate else x['Price'], axis=1)
Answered By: Pedro Rocha
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.