gpt4 book ai didi

python - 数据帧尾随统计

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:31 24 4
gpt4 key购买 nike

问题:

是否有计算跟踪统计数据的内置方法?

背景:

滚动方法看起来几乎很完美,但我只能让它提供向前滚动而不是向后滚动。我想计算第 1 列中第 1:4 列的平均值,而不是默认的第 4 列。

我知道这可以通过一些操作和/或循环来完成(或者可能就像删除列 1:4 一样),但如果有一个简单的内置解决方案那就太棒了。

当前代码:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(100, 110, size=(5, 10)),
columns=list([x for x in range(1, 11)]))

df

1 2 3 4 5 6 7 8 9 10
0 106 108 104 108 108 109 105 102 106 102
1 105 106 107 102 100 106 106 100 101 103
2 103 101 102 100 107 105 106 100 107 105
3 104 104 107 109 105 106 108 107 109 100
4 103 100 101 106 101 102 101 100 103 100

df.rolling(window=4, axis=1).mean()

1 2 3 4 5 6 7 8 9 10
0 NaN NaN NaN 106.5 107.00 107.25 107.5 106.0 105.50 103.75
1 NaN NaN NaN 105.0 103.75 103.75 103.5 103.0 103.25 102.50
2 NaN NaN NaN 101.5 102.50 103.50 104.5 104.5 104.50 104.50
3 NaN NaN NaN 106.0 106.25 106.75 107.0 106.5 107.50 106.00
4 NaN NaN NaN 102.5 102.00 102.50 102.5 101.0 101.50 101.00

最佳答案

pandas.DataFrame.shift() 是否有资格作为简单的内置解决方案

window_size = 4
df.rolling(window=window_size, axis=1).mean().shift(1-window_size, axis=1)

给予:

       1       2       3       4       5       6       7   8   9   10
0 106.00 106.75 107.50 107.25 106.75 105.25 103.50 NaN NaN NaN
1 104.25 105.75 106.00 107.25 105.75 104.25 104.25 NaN NaN NaN
2 102.50 102.25 103.75 103.75 105.00 104.00 102.50 NaN NaN NaN
3 104.00 105.75 105.25 105.25 107.25 106.25 104.75 NaN NaN NaN
4 107.75 105.50 104.25 102.75 103.00 103.75 105.00 NaN NaN NaN

关于python - 数据帧尾随统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180056/

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