Python - Numpy或Pandas(也可以)广播

xtfmy6hx  于 2023-05-12  发布在  Python
关注(0)|答案(2)|浏览(150)

我有一个numpy array-2D(也可以使用pandas DatarFame),里面充满了数字,我需要在一列中的最后n行中创建/替换这些数字。我有一个巨大的numpy数组。形状像[10000:10000]

示例(有限的形状仅用于说明):

Numpy Array:

[[10, 30, 8, 1],
 [11, 5, 19, 12],
 [12, 18, 15, 6],
 [13, 10, 21, 9],
 [14, 67, 14, 2],
 [15, 13, 12, 6]]

平均n = 3

所以代码应该在迭代中取最后3个数字并取crate平均值

Numpy Array:

[[12.5, 23.5, 14.83333333, 5.833333333],
 [12, 10.33333333, 18.33333333, 9],
 [13, 31.66666667, 16.66666667, 5.666666667],
 [14, 30, 15.66666667, 5.333333333]]

说明:

  • 14是15,14,13的平均数
  • 18.3333333是数字21、15、19的平均数
  • 9是数字9、6、12的平均数

结果应该是函数在列维度中取最后n个值并求其平均值。
我能够通过2 for循环和标准python代码来完成它,但这需要很多时间。

cngwdvgl

cngwdvgl1#

你不需要循环你的数据。使用Pandas,您可以执行rolling_mean

import pandas as pd
import numpy as np

arr = np.array([[10, 30,  8,  1],
                [11,  5, 19, 12],
                [12, 18, 15,  6],
                [13, 10, 21,  9],
                [14, 67, 14,  2],
                [15, 13, 12,  6]])

n = 3
df = pd.DataFrame(arr)
out = df.rolling(n).mean().iloc[n-1:]
print(out)

# Output
      0          1          2         3
2  11.0  17.666667  14.000000  6.333333
3  12.0  11.000000  18.333333  9.000000
4  13.0  31.666667  16.666667  5.666667
5  14.0  30.000000  15.666667  5.666667

使用numpy,你可以:

# Adapted from https://stackoverflow.com/q/14313510/15239951
out = np.cumsum(arr, axis=0)
out[n:] -= out[:-n]
out = out[n-1:] / n
print(out)

# Output
array([[11.        , 17.66666667, 14.        ,  6.33333333],
       [12.        , 11.        , 18.33333333,  9.        ],
       [13.        , 31.66666667, 16.66666667,  5.66666667],
       [14.        , 30.        , 15.66666667,  5.66666667]])
vddsk6oq

vddsk6oq2#

我也用循环法解决了这个问题,你可以和你的比较一下。

def process(data,n):
    for i in range(n):
        data[:][i]=np.mean(data[:][i:i+n],axis=0)
    return data[:][:-n+1]

相关问题