title: Calculating Precision and Recall from confusion matrix in python
body: <p>I have a confusion matrix for 2 classes with pre-calculated totals in a pandas dataframe format:</p>
  
  <pre><code>    Actual_class  Predicted_class_0  Predicted_class_1  Total  
  0         0              39                 73           112   
  1         1              52                561           613          
  2        All             91                634           725        
  </code></pre>
  
  <p>I need to calculate precision and recall using a loop as I need a general case solution for more classes.</p>
  
  <p>Precision for class 0 would be 39/91 and for class 1 would be 561/634.<br>
  Recall for class 0 would be 39/112 and for class 1 would be 561/613.</p>
  
  <p>So I need to iterate by diagonal and totals to get the following results  </p>
  
  <pre><code>    Actual_class  Predicted_class_0  Predicted_class_1  Total Precision Recall  
  0         0              39                 73           112     43%     35%
  1         1              52                561           613     88%     92%     
  2        All             91                634           725    
  </code></pre>
  
  <p>Totals (All row and Total column) will be removed afterwords, so there is no point to calculate them. </p>
  
  <p>I tried the following code, but it doesn't go by diagonal and loses data for the class 0:</p>
  
  <pre><code>cols = [c for c in cross_tab.columns if c.lower()[:4] == 'pred'] 
  
  for c in cols:  
      cross_tab["Precision"] = cross_tab[c]/cross_tab[c].iloc[-1]
  
  for c in cols:  
      cross_tab["Recall"] = cross_tab[c]/cross_tab['Total']
  </code></pre>
  
  <p>I'm novice to pandas matrix operations and really need your help.</p>
  
  <p>I'm sure there is a way to proceed without pre-calculating totals.</p>
  
  <p>Thank you very much!!!</p>