Pandas:设置滑动窗口以迭代行并应用函数

4

我有以下在pandas中的DataFrame:

[A]             [measure]
17442.77000     32.792658
17442.8         name1
17442.95100     32.792658
--
--
17517.49200     37.648482
17517.5         name2
17518.29600     37.648482
--
--
17565.77600     38.287118
17565.8         name3
17565.88800     38.287118
--
--
17596.93700     41.203340
17597.2         name4
17597.29700     41.203340
--
--
17602.16400     41.477979
17602.5         name5
17602.83900     41.612774
--
--
17618.16400     42.479890
17618.4         name6
17618.71100     42.681591

我想遍历每三行数据并应用一个函数,该函数需要:

f(x)= df.iloc[0,1]+(df.iloc[2,1]-df.loc[0,1])*((df.iloc[1,0]-df.iloc[0,0])/(df.iloc[2,0]-df.iloc[0,0])).

理想情况下,我希望以字典格式返回结果,这样我就可以获得:
Results={"name1": f(x), "name2": f(x),...}

如果您有关于如何在pandas中设置滑动窗口的任何提示,我们将非常感谢。

1个回答

3
如果我理解得正确,这个应该可以运行:

def f(x):
    return df.iloc[0,1]+(df.iloc[2,1]-df.iloc[0,1])*((df.iloc[1,0]-df.iloc[0,0])/(df.iloc[2,0]-df.iloc[0,0]))

在这里,您可以使用[[::3]],以步长为3,应用滚动窗口window=3min_periods=1

a = df.rolling(window=3, min_periods=1).apply(f)[::3].reset_index(drop=True)

当你将列 measurement 的字符串保存到列表 s 中后:

s = list(i for i in df['measure'] if isinstance(i, basestring))

s 分配为字典 d 的键。

d = a.T.to_dict('list')
for index, k in enumerate(list(s)):
    d[k] = d[index]
    del d[index]

谢谢Joe的详细解释。df.rolling正是我在寻找的! - RJF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接