How do I make the window roll across the rows instead of the columns in Python?

Viewed 76

I have the following code that rolls a window of size 3 column-wise (i.e. downwards as depicted in green in the image). However, I'd like the window to roll row-wise (i.e. rightwards as depicted in blue in the image). enter image description here

window_size = 3 

numbers_series = X  #X is my dataframe
windows = numbers_series.rolling(window_size)
moving_averages = windows.mean()
moving_averages_list = moving_averages.values.tolist()
without_nans = moving_averages[window_size - 1:]
print(without_nans)

The output column-wise is: enter image description here

But this is not what I want - I'd like it to give me the mean of the windows row-wise. How do I go about achieving this?

EDIT: After editing the above code to include axis=1 in the rolling function, this is the output I get: enter image description here

I'm not sure how the values of 520.67, 635.33, etc are computed above. I was expecting the following (first cell: 788 + 43 + 345)/3 = 392, etc...):

enter image description here

1 Answers

pandas.DataFrame.rolling has a parameter for the axis. DataFrame.rolling

DataFrame.rolling(
    window, 
    min_periods=None, 
    center=False, 
    win_type=None, 
    on=None, 
    axis=0, # Set axis to 1.
    closed=None) 
Related