I am trying to make sense out of some data, here is the Pandas data frame:
In [1]: import pandas as pd
In [2]: df = pd.read_csv('c1.csv')
In [3]: df.head(2)
Out[3]:
year city country avg_temp
0 1849 Abidjan Côte D'Ivoire 25.58
1 1850 Abidjan Côte D'Ivoire 25.52
All I want is to know if the year is greater than 2000 and avg_temp is less than 20, then what's the mean() and I get 2 different answers:
In [10]: (df.query('year > 2000')['avg_temp'] < 20).mean()
Out[10]: 0.5629877369007804
In [11]: ((df.year > 2000) & (df.avg_temp < 20)).mean()
Out[11]: 0.03540828203222504
In [12]: ((df['year'] > 2000) & (df['avg_temp'] < 20)).mean()
Out[12]: 0.03540828203222504
I can't figure out which one is correct
avg_temp
or the mean of the boolean truth vector? The former will be, as it seems, the average average temperature, the latter will be the number of rows that fit your query divided by the total number of rows. $\endgroup$.mean()
, each line is a boolean Series, and applying mean to those gives the percentage of city-years with avg_temp<20. The two different answers are explained by @rajatkabra. For average temperatures instead, you need to use the binary series to slice the dataframe, then average the temperature column. $\endgroup$