Issue
I would like to get the indexes of the elements in each rolling window of a Pandas Series.
A solution that works for me is from this answer to an existing question: I get the window.index
for each window
obtained from the rolling
function described in the answer. I am only interested in step=1
for the aforementioned function.
But this function is not specific for DataFrames and Series, it would work on basic Python lists. Isn't there some functionality that takes advantage of Pandas rolling operations?
I tried the Rolling.apply
method:
s = pd.Series([1, 2, 3, 4, 5, 6, 7])
rolling = s.rolling(window=3)
indexes = rolling.apply(lambda x: x.index)
But it result in a TypeError: must be real number, not RangeIndex
. Apparently, the Rolling.apply
method only accepts functions that return a number based on each window. The functions cannot return other kinds of objects.
Are there other methods of the Pandas Rolling
class I could use? Even private methods.
Or are there any other Pandas-specific functionalities to get the indexes of overlapping rolling windows?
Expected output
As output, I expect some kind of list-of-lists object. Each inner list should countain the index values of each window.
The original s
Series has [0, 1, 2, 3, 4, 5, 6]
as index.
So, rolling with a window=3
, I expect as outcome something like:
[
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
]
Solution
The apply
function after rolling
must return a numeric value for each window. One possible workaround is to use a list comprehension to iterate over each window and apply the custom transformation as required:
[[*l.index] for l in s.rolling(3) if len(l) == 3]
Alternatively you can also use sliding_window_view
to accomplish the same:
np.lib.stride_tricks.sliding_window_view(s.index, 3)
Or even an list comprehension would do the job just fine:
w = 3
[[*s.index[i : i + w]] for i in range(len(s) - w + 1)]
Result
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
Answered By - Shubham Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.