Search code examples
pythonpandaspymc3

Percentage match in pandas Dataframe


Is there a function that tells the percentage or number of matches in a pandas DataFrame without doing something like this...

len(trace_df[trace_df['ratio'] > 0]) / len(trace_df)
0.189

len(trace_df[trace_df['ratio'] <= 0]) / len(trace_df)
0.811

There must be a more Pythonic or at least elegant way of doing this.


Solution

  • The most pythonic way of finding a percentage of a column that is true is to simply take the mean of the boolean expression.

    (trace_df['ratio'] > 0).mean()