Reputation: 59
I want to generate a new column based on the function of another column and the row before the current row.
i.e.
NewColumn_{n} = OldColumn_{n} * 0.6 + NewColumn_{n-1} * 0.4
Is it possible I could do this without using iterrows
?
I saw this post: How to constuct a column of data frame recursively with pandas-python?
But I'm wondering if there is another function/package or tricks within Pandas?
Something like purrr
in R?
Upvotes: 1
Views: 2269
Reputation: 20669
You can write a custom func here and use df.apply
def func(s): # s is `Series`
newColumn = [0]
for i, val in enumerate(s):
newColumn.append(val*0.6 + newColumn[i]*0.4)
return newColumn[1:]
df['new'] = df[['old']].apply(func) #Don't use df['old'] that would call
#Series.apply which applies func element-wise
old new
0 1 0.600
1 2 1.440
2 3 2.376
Upvotes: 1