1

I am rendering/displaying a list of predictions to a webpage using FLASK API. The list has three elements: ReqNum, Predictions and the probability of the predictions. I am able to show each record in a row properly. But, I can't divide the row into three columns for each of the above mentioned elements. I am converting the data frame to list and then passing it to the webpage. Below is the code:

from flask import Flask, abort, request,render_template, json, render_template_string
from DataPreparationv4 import Data_Preprocess
import numpy as np
import pandas as pd
import pickle


pd.options.mode.chained_assignment = None

filename = 'Test2.pkl'
loaded_model = pickle.load(open(filename, 'rb'))

app = Flask(__name__)

@app.route("/", methods=['GET'])
def Predictions():
    Base_Data = pd.read_csv('Test.csv')
    DataSet1 = Data_Preprocess(Base_Data)

    CaseNumber = DataSet1[1]
    DataSet1 = DataSet1[0]
    result = loaded_model.predict(DataSet1)

    prob = loaded_model.predict_proba(DataSet1)

    Predictions = pd.DataFrame({'CTA Code':result,'Prob1':prob[:,0],'Prob2':prob[:,1]})
    Predictions['Probability'] = np.where(Predictions['Prob1'] > Predictions['Prob2'], 
               Predictions['Prob1'], Predictions['Prob2'])

    Predictions['CaseNumber'] = CaseNumber['Case Number']

    CTA_Map = [['Y',1],['N',0]]
    CTA_Map = pd.DataFrame(CTA_Map,columns=['CTA Met','CTA Code'],dtype=float)

    Predictions = pd.merge(Predictions,CTA_Map[['CTA Code','CTA Met']],on='CTA Code', how='left')
    Predictions =  Predictions.drop(['CTA Code','Prob1','Prob2'], axis=1)
    Predictions = Predictions[['CaseNumber', 'CTA Met', 'Probability']]
    df_list = Predictions.values.tolist()

    return render_template('hello13.html', my_list=df_list)
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000,debug = True)

Below is the code for HTML template:

<html>
<body>
     <table>
         <tbody>
         {# here we iterate over every item in our list#}
         {% for item in my_list %}
             <tr><td>{{ item }}</td></tr>
         {% endfor %}
         </tbody>
     </table>
 </body>
 </html>

View on the browser of the output:

Sample output on browser

  • What should I do to get three columns for each element in the table row.

Since my approach of data frame to list leads to loss of column names or column headers. Hence,

  • Is there a way to display the data frame so that I do not lose the column names/headers.
  • Or how can I pass the column headers to the HTML table column header using my current technique of data frame to list.

Please guide me in how to resolve this issue. I am still a newbie in Python hence my knowledge on concepts are till evolving.

Hence requesting you to please guide me on the concepts also.

kbsudhir
  • 415
  • 1
  • 6
  • 15
  • your sample is a bit confusing, everything is called `Predictions` :) I'm not sure how you can access each information in the object `item` inside your for-loop, could you print a sample of the final`df_list` ? – PRMoureu Jul 08 '18 at 18:47
  • @PRMoureu I have added the screenshot of the sample output from the browser to the post. It is missing the column header and the has only one column instead of three columns which I am targeting to have. – kbsudhir Jul 08 '18 at 19:41

1 Answers1

1

If you can control that each row contains exactly 3 members, one easy option is to unpack the 3 items directly in the for-loop :

{% for num, prediction, prob in my_list %}
    <tr>
        <td>{{ num }}</td>
        <td>{{ prediction }}</td>
        <td>{{ prob }}</td>
    </tr>
{% endfor %}
PRMoureu
  • 12,817
  • 6
  • 38
  • 48
  • Thanks @PRMoureu I have just one more question, my last column in probability in decimels. Is there any way I can convert it to % in the table. – kbsudhir Jul 08 '18 at 20:06
  • of course, you can perform some operations in a template, like `{{ prob*100 }}%`. It may be better to handle this kind of operation inside the view, and pass the correct value to the template – PRMoureu Jul 08 '18 at 20:12
  • Gr8, it works like a charm. I apologize for asking another question on the decimal points in probability column. I want to reduce it to two digits only. How can I do about doing it. – kbsudhir Jul 08 '18 at 20:22
  • this one you could have find yourself, like in this post https://stackoverflow.com/a/8940627/6655211 `{{ '{0:.2f}'.format(prob*100) }}%` (you should not ask multiple questions in one) – PRMoureu Jul 08 '18 at 20:30
  • Thanks for your time and efforts @PRMoureu. Surely will not multiple questions in one. – kbsudhir Jul 08 '18 at 20:32
  • ;) again, it may be better to handle that before rendering the template, just after you do the calculation – PRMoureu Jul 08 '18 at 20:34
  • Surely will remember this best practice – kbsudhir Jul 08 '18 at 20:35