gpt4 book ai didi

python - 如何应用以调用者作为参数的函数

转载 作者:行者123 更新时间:2023-12-01 05:25:10 25 4
gpt4 key购买 nike

我试图在数据帧上逐列运行 np 的相关函数,但我想要运行的相关性是系列本身。例如,假设 df 是我们的数据帧,ts 是 df 的第一列。我想调用 np.correlate(ts, ts, method="full")

df = pd.DataFrame([[1,1],[2,2],[3,3],[4,4],[5,5]], index=range(5), columns=list("ab"))

def acf(R):
"""
Calcualte the auto correlation function of a series with lag 0 up to the length
of the series.
"""
y = R - R.mean()
result = y.apply(np.correlate, (y, "full"))
result = result[len(result)//2:]
result /= result[0]
return result

acf(df)

NameError: name 'y' is not defined

我应该怎么做才能实现这个目标?

最佳答案

pandas.Series 对象往往与 numpy 函数配合良好,因此将函数定义为

def acf(R):
"""
Calcualte the auto correlation function of a series with lag 0 up to the length
of the series.
"""
y = R - R.mean()
result = np.correlate(y, y, 'full')
result = result[len(result)//2:]
result /= result[0]
return result

然后使用 df.apply(acf) 将其应用到 DataFrame 应该可以工作。

In [4]: import numpy as np

In [5]: import pandas as pd
...: def acf(R):
...: """
...: Calcualte the auto correlation function of a series with lag 0 up to the length
...: of the series.
...: """
...: y = R - R.mean()
...: result = np.correlate(y, y, 'full')
...: result = result[len(result)//2:]
...: result /= result[0]
...: return result
...: df = pd.DataFrame([[1,1],[2,2],[3,3],[4,4],[5,5]], index=range(5), columns=list("ab"))
...:

In [6]: df.apply(acf)
Out[6]:
a b
0 1.0 1.0
1 0.4 0.4
2 -0.1 -0.1
3 -0.4 -0.4
4 -0.4 -0.4

关于python - 如何应用以调用者作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com