繁体   English   中英

Pandas pd.apply function 与 python 缓存一起使用无法进行哈希处理”

[英]Pandas pd.apply function work with python caches cannot be hashed"

我有一个 df,你可以通过运行以下代码来获得它:

import pandas as pd
from io import StringIO
from functools import lru_cache

df = """
  contract      EndDate     
  A00118        123456
  A00118        12345   
"""
df = pd.read_csv(StringIO(df.strip()), sep='\s+')

output 是:

    contract    EndDate
0   A00118     123456
1   A00118     12345

然后我对每一行应用了一个逻辑:

def var_func(row,n):
    res=row['EndDate']*100*n
    return res

df['annfact'] = df.apply(lambda row: var_func(row,10), axis=1)

output 是:

    contract    EndDate annfact
0   A00118     123456   123456000
1   A00118     12345    12345000

但是,如果我在这个 function 上应用 python lru_cache:

@lru_cache(maxsize = None)
def var_func(row,n):
    res=row['EndDate']*100*n
    return res

df['annfact'] = df.apply(lambda row: var_func(row,10), axis=1)

错误:

TypeError: ("'Series' objects are mutable, thus they cannot be hashed", 'occurred at index 0')

有朋友可以帮忙吗?我想申请python lru_cache到pd.apply function。由于某些原因我只能使用pd.apply function,而不是向量化numpy方法。

文档

由于字典用于缓存结果,位置和关键字 arguments 到 function 必须是可哈希的。

使用df.apply(..., axis=1) ,您传递的是不可散列的行(这是一个 Series 对象),因此会出现错误。

解决此问题的一种方法是在列上应用var_func

@lru_cache(maxsize = None)
def var_func(row, n):
    return row*100*n

df['annfact'] = df['EndDate'].apply(var_func, n=10)

对于您的具体示例,最好使用矢量化操作:

df['annfact'] = df['EndDate']*100*n

我们还可以将每一行转换为可散列的内容。 由于您想继续引用列名,我们可以使用collections.namedtuple

@lru_cache(maxsize = None)
def var_func(row, n):
    res=row.EndDate*100*n
    return res

from collections import namedtuple
df_as_ntup = namedtuple('df_as_ntup', df.columns)
df['annfact'] = df.apply(lambda row: var_func(df_as_ntup(*row), 10), axis=1)

Output:

  contract  EndDate    annfact
0   A00118   123456  123456000
1   A00118    12345   12345000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM