M3105 - 8 months ago 21

Python Question

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`

`Totals`

`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`

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
```