1

I saw a post about creating recurrsive sum recursive cumulative sums I have modified that to add a decay "factor"

def rec(n, factor):
    if len(n) < 2: return n
    n[1] = factor*n[0] + n[1]
    return [n[0]] + rec(n[1:], factor)

print(rec([1,2,3,4], 0.5))
#[1, 2.5, 4.25, 6.125]

The function works well for list. I would like to change it to used on pandas series. So I can apply to a DataFrame for each group of 'ID' using 'transform'. something like below:

import pandas as pd

df_dic = {'ID': [1,1,1,1,2,2,2],
         'channel': [1,2,3,4,3,2,4]}
df = pd.DataFrame.from_dict(df_dic)

output = df.groupby(['ID'])['channel'].transform(rec, 0.5)

In order to do that I guess I need to revise the function to using pandas series instead of list. Is there a easy way to do that?

Gavin
  • 1,411
  • 5
  • 18
  • 31

1 Answers1

0

in such case you able to convert Series to list, something like this:

def rec(n, factor):
    if (type(n) != list): n = list(n)  # <---- here it is
    if len(n) < 2: return n
    n[1] = factor*n[0] + n[1]
    return [n[0]] + rec(n[1:], factor)

print(rec([1,2,3,4], 0.5))
#[1, 2.5, 4.25, 6.125]


import pandas as pd

df_dic = {'ID': [1,1,1,1,2,2,2],
     'channel': [1,2,3,4,3,2,4]}
df = pd.DataFrame.from_dict(df_dic)

output = df.groupby(['ID'])['channel'].transform(rec, 0.5)


Out[1]:
    0    1.000
    1    2.500
    2    4.250
    3    6.125
    4    3.000
    5    3.500
    6    5.750
Alex
  • 1,118
  • 7
  • 7