简体   繁体   中英

(Python): Moving average using 2D array

I have a 2D list and I want to calculate the moving average along the columns numbers. I have the following code. Does anyone know a numpy method which returns a new 2D list with the moving average of all columns?

v = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

print((v[0][0]+v[1][0])/2)

Returns

2.5

IIUC and you have no problem using pandas :

import pandas as pd

v = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

pd.DataFrame(v).rolling(3,axis=0, min_periods=1).mean().values

Output:

array([[1. , 2. , 3. ],
       [2.5, 3.5, 4.5],
       [4. , 5. , 6. ]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM