Search code examples
pythonpandasdataframeaveragemean

Find the average of last 25% from the input range in pandas


I have successfully imported temperature CSV file to Python Pandas DataFrame. I have also found the mean value of specific range:

df.loc[7623:23235, 'Temperature'].mean()

where 'Temperature' is Column title in DataFrame.

I would like to know if it is possible to change this function to find the average of last 25% (or 1/4) from the input range (7623:23235).


Solution

  • Yes, you can use the quantile method to find the value that separates the last 25% of the values in the input range and then use the mean method to calculate the average of the values in the last 25%.

    Here's how you can do it:

    quantile = df.loc[7623:23235, 'Temperature'].quantile(0.75)
    
    
    mean = df.loc[7623:23235, 'Temperature'][df.loc[7623:23235, 'Temperature'] >= quantile].mean()