簡體   English   中英

將 Flask 表單數據輸入轉化為 Pandas Dataframe 用於 ML 建模

[英]Take Flask Form Data Input and Turn it Into Pandas Dataframe For ML Modeling

我正在構建一個小燒瓶應用程序來從 HTML 中獲取表單數據。 我想將此表單數據(每個選擇放入一列)轉換為 Pandas DataFrame。 然后我將使用一個 pickle 文件來創建這個 DataFrame 的預測。 我現在遇到的問題是不知道如何將我輸入的數據轉換為 Pandas DataFrame。

我相信我的可變結果中有我的請求信息,但我不確定如何從這里開始。

應用程序.py文件

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
    colours = ['RED', 'BLUE', 'BLACK', 'ORANGE']
    return render_template('student.html', colours = colours)

@app.route('/result',methods = ['POST', 'GET'])
    def result():
    if request.method == 'POST':
        result = request.form
        return render_template("result.html", result = result)

if __name__ == '__main__':
    app.run(debug=True, port=8080) #run app in debug mode on port 5000

學生.html

<html>
<body>
    <form action="http://localhost:8080/result" method="POST">
        <p>Year of Test <input type="text" name="TestYear" /></p>
        <p>Yeah of Student <input type="text" name="StudentYear" /></p>
        <p>State of Student <input type="text" name="StudentState" /></p>
        <p>Origin State <input type="text" name="OriginState" /></p>
        <p>Shirt Color <select name=color method="GET" action="/">
            {% for colour in colours %}
            <option value="{{colour}}" SELECTED>{{colour}}</option>"
            {% endfor %}
        </select></p>
        <p><input type="submit" value="submit" /></p>
    </form>
</body>
</html>

你必須像這樣傳遞你的數據:

@app.route('/result/<name>',methods = ['POST', 'GET'])
def result(name):
   # you can use your variable name in here given from the html form.

這是你想要的 ?

HTML 表單輸入轉換為Dictionary ,然后轉換為Pandas 數據框

@app.route('/predict/<target>',methods=['GET','POST'])
def predict(target):
    d = None
    if request.method == 'POST':
        print('POST received')
        d = request.form.to_dict()
    else:
        print('GET received')
        d = request.args.to_dict()
    print(d)
    print(d.keys())
    print(d.values())

    print("Dataframe format required for Machine Learning prediction")
    df = pd.DataFrame([d.values()], columns=d.keys())
    print(df)

    return 'Predicting %s' %target

在瀏覽器上,粘貼 GET url - http://localhost:8080/predict/TTT?a=1&b=2&c=3

或者

使用 POST 命令執行:

curl -d "a=1&b=2&c=3" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:8080/predict/TTT

輸出:

127.0.0.1 - - [28/Aug/2020 04:46:25] "GET /predict/TTT?a=1&b=2&c=3 HTTP/1.1" 200 -
GET received
{'a': '1', 'b': '2', 'c': '3'}
dict_keys(['a', 'b', 'c'])
dict_values(['1', '2', '3'])
Dataframe format required for Machine Learning prediction
   a  b  c
0  1  2  3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM