I've been trying to convert some of my functions where I use a for loop by using list comprehension. Here is my first version of the function,
def adstocked_advertising(data, adstock_rate):
'''
Transforming data with applying Adstock transformations
data - > The dataframe that is being used to create Adstock variables
adstock_rate -> The rate at of the adstock
ex. data['Channel_Adstock'] = adstocked_advertising(data['Channel'], 0.5)
'''
adstocked_advertising = []
for i in range(len(data)):
if i == 0:
adstocked_advertising.append(data[i])
else:
adstocked_advertising.append(data[i] + adstock_rate * adstocked_advertising[i-1])
return adstocked_advertising
I want to convert it to this,
def adstocked_advertising_list(data, adstock_rate):
adstocked_advertising = [data[i] if i == 0 else data[i] + adstock_rate * data[i-1] for i in range(len(data))]
return adstocked_advertising
However, when viewing the df after running both functions I get two different values.
data['TV_adstock'] = adstocked_advertising_list(data['TV'], 0.5)
data['TV_adstock_2'] = adstocked_advertising(data['TV'], 0.5)
here is output,
data.head()
data.tail()
I am not too sure why the first two rows are the same and then from there the numbers are all different. I am new to list comprehension so I may be missing something here.