python - 如何使用列表将用户定义的函数更改为pandas系列

标签 python pandas

我看到一篇关于创建递归求和的帖子 recursive cumulative sums 我对其进行了修改以添加衰减“因子”

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]

该函数适用于列表。我想将其更改为用于 pandas 系列。因此,我可以使用“transform”将每组“ID”应用于 DataFrame。如下所示:

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)

为了做到这一点,我想我需要修改该函数以使用 pandas 系列而不是列表。有没有简单的方法可以做到这一点?

最佳答案

在这种情况下,您可以将系列转换为列表,如下所示:

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

关于python - 如何使用列表将用户定义的函数更改为pandas系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647984/

相关文章:

python - 在 python/tornado 中根据 rfc 5987 对文件名进行编码

Python: bool 值没有按预期工作

Python Mechanize/BeautifulSoup Scraping(迭代字典)

python - 从 mongodb、python3 中的字符串进行查询

python - 匹配值并在 python 中获取其列标题

python - 在 Python 中附加 Pickle 文件

python - 过滤多个变量的每个级别

关于 write() 和 truncate() 的 Python 问题

csv - Panda read_csv 中的编码错误

python - pandas 列划分 ValueError (putmask : mask and data must be the same size)