Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Series argument function memoization

I want to memoize a function with mutable parameters (Pandas Series objects). Is there any way to accomplish this?

Here's a simple Fibonacci example, the parameter is a Pandas Series where the first element represents the sequence's index.

Example:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n.iloc[0] == 1 or n.iloc[0] == 2:
        return 1
    min1 = n.copy()
    min1.iloc[0] -=1
    min2 = n.copy()
    min2.iloc[0] -= 2 
    return fib(min1) + fib(min2)

Call function:

fib(pd.Series([15,0]))

Result:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

The intended use is more complex, so I posted this useless but simple example.

like image 764
Jorge Barrios Avatar asked Jul 01 '26 08:07

Jorge Barrios


1 Answers

Several options:

  • Convert the mutable objects to something immutable such as a string or tuple.
  • Create a hash of the mutable objects and use that as the memo dict key. Risk of hash clashes.
  • Create an immutable subclass which implements the __hash__() function.
like image 150
Calvin Avatar answered Jul 04 '26 14:07

Calvin