使用df.rolling()获取全部rolls

2024-05-14 19:41:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几点df

      Price     Price2    Count  perc_change
0  0.000868    33782.17     4     1.000000
1  0.000872    33224.89     3     0.460829
2  0.000875    84110.85     7     0.344037
3  0.000878    67686.15     4     0.342857
4  0.000880    121400.22    4     0.227790

使用以下代码时:

def test(x):
    print(x)
    print("------")
    return x[1]

x = df.rolling(2, axis=0).apply(test)

我发现自己有以下输出:

[0.000868 0.000872]
------
[0.000872 0.000875]
------
[0.000875 0.000878]
------
[0.000878 0.00088 ]
------
[33782.17 33224.89]
------
[33224.89 84110.85]
------
[84110.85 67686.15]
------
[ 67686.15 121400.22]
------
[1.         0.46082949]
------
[0.46082949 0.3440367 ]
------
[0.3440367  0.34285714]
------
[0.34285714 0.22779043]
------
[4. 3.]
------
[3. 7.]
------
[7. 4.]
------
[4. 4.]
------

我试图实现的输出如下:

[0.000868    33782.17     4     1.000000]
[0.000872    33224.89     3     0.460829]
------
[0.000875    84110.85     7     0.344037]
[0.000878    67686.15     4     0.342857]
[0.000880    121400.22    4     0.227790]
------

我尝试将axis参数切换为1,但没有成功

非常感谢你的帮助


Tags: 代码testdf参数returndefcountchange
1条回答
网友
1楼 · 发布于 2024-05-14 19:41:48

我不确定您的最终结果是什么,但这是实现打印输出的一种方法:

def test(x):
    print(df.loc[x])
    print("   ")
    return x[1]

df.index.to_series().rolling(2).apply(test, raw=True)

输出:

        Price    Price2  Count  perc_change
0.0  0.000868  33782.17      4     1.000000
1.0  0.000872  33224.89      3     0.460829
   
        Price    Price2  Count  perc_change
1.0  0.000872  33224.89      3     0.460829
2.0  0.000875  84110.85      7     0.344037
   
        Price    Price2  Count  perc_change
2.0  0.000875  84110.85      7     0.344037
3.0  0.000878  67686.15      4     0.342857
   
        Price     Price2  Count  perc_change
3.0  0.000878   67686.15      4     0.342857
4.0  0.000880  121400.22      4     0.227790

相关问题 更多 >

    热门问题