Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

python - Pandas rolling values

How do I obtain the rolling values of some length n of a pandas series of value ?

For example, if I have the following:

df = pd.DataFrame({'temperature': [0, 1, 2, np.nan, 4, 2, 0.8, 4, 8.8, 7.12]})

how do I obtain the moving values of length n, i.e. something like, if n=3:

[NaN, NaN, 0], [NaN, 0, 1],..., [4, 8.8, 7.12]

EDIT: If I use pandas rolling, as:

roll = pd.Series.rolling(df, 3).mean()

then roll is the moving averages of the series. Here, I do not want the averages of every moving set of 3 values, but these sets of 3 values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need first add NaNs and then this solution:

N = 3
x = np.concatenate([[np.nan] * (N-1), df['temperature'].values])

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
print (rolling_window(x, N))
[[  nan   nan  0.  ]
 [  nan  0.    1.  ]
 [ 0.    1.    2.  ]
 [ 1.    2.     nan]
 [ 2.     nan  4.  ]
 [  nan  4.    2.  ]
 [ 4.    2.    0.8 ]
 [ 2.    0.8   4.  ]
 [ 0.8   4.    8.8 ]
 [ 4.    8.8   7.12]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...