M3105 M3105 - 4 months ago 6
Python Question

How to get the Average of a specific category via Python

I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv

import pandas as pd
import numpy as np

#loading the data into data frame
X = pd.read_csv('demo.csv')


the two columns of interest are the
Category
and
Totals
column:

Category Totals estimates
2 2777 0.43
4 1003 0.26
4 3473 0.65
4 2638 0.17
1 2855 0.74
0 2196 0.13
0 2630 0.91
2 2714 0.39
3 2472 0.51
0 1090 0.12


I'm interested in finding the average for the Totals corresponding with
Category
2. I know how to do this on excel, I would just filter to only show category 2 and get the average(which ends up being 2745.5) but how would I code this via Python?

Answer

You can restrict your dataframe to the subset of the rows you want(Category=2), followed by taking mean of the columns corresponding to Totals column as follows:

df[df['Category'] == 2]['Totals'].mean()
2745.5
Comments