K
K
Kirill Petrov2020-05-10 12:11:34
Python
Kirill Petrov, 2020-05-10 12:11:34

How to get the average of the last n rows into a new column in pandas?

Greetings. I'll write it in more detail, I don't know how to google it.

There is a table:

a = 
df = pd.DataFrame(a, columns=['low', 'high'])
df

5eb7c3030a84f228407417.png

No problem, it turns out to calculate the average between the columns
df = df.assign(hl2 = (df.low + df.high) / 2)
df

5eb7c3bc32030064976596.png

But how to calculate the average for each last 3 rows?
Tried like this:
df = df.assign(mean3 = df.tail(3).hl2.mean())
df

And I got the result everywhere in general for the last 3 lines
5eb7c448e51ce002729515.png

. You can, of course, sort through the loop, but with large data this is very inefficient. I think there must be some native method for this?

For example, the prometheus monitoring system uses a method in the rate request that does something similar.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Petrov, 2020-05-10
@Recosh

Found the answer. rolling method

df = df.assign(mean3 = df.rolling(3, min_periods=1).hl2.mean())
df

5eb7cfec44a3d682733791.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question