简体   繁体   中英

Python Evaluate Values on Sheet Using Pandas Read then Write on the File

Hello I'm new to web app dev. I'm trying to make an app, which manipulates a csv file.

Let me paste my code before I state my problem below:

#!/usr/bin/env python
import os
import pandas as pd
from flask import Flask, request,render_template, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename





# create app
app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = '/home/Firiyuu77/mysite/uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','csv','xlsx'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']


@app.route('/')
def main():
    return render_template('index.html')

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    # Get the name of the uploaded file
    file = request.files['file']
    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to
        # the upload folder we setup
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
        return redirect(url_for('uploaded_file',
                                filename=filename))

# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(
        host="0.0.0.0",
        port=int("80"),
        debug=True
    )


#--------------------------------------------------------

#--------------------------------------------------------

#--------------------------------------------------------UNFINISHED PART

def forecastvalues():


  fileName = "test.csv"
  records = pd.read_csv(fileName, header=None, nrows=5)

  for i in records:
    rem = records.iloc([i], [0])
    sold1 = records.iloc([i], [1])
    sold2 = records.iloc([i], [2])

    rem = int(rem)
    sold1 = int(sold1)
    sold2 = int(sold2)
    result = forecast(rem,sold1,sold2)
    records.set_value([i], [4], result)
    pd.to_csv('test.csv')





#--------------------------------------------------------
#
#
#
#
# ------------------------------------------------------------
# MAIN Program
# ------------------------------------------------------------



#------------------------------------------------------------------------------------------------







def calculate(r,t,l):
    return ((l+t)/2)*3


def forecast(rem, sold1, sold2):


     if (rem == 0 and sold1 == 0 and sold2 ==0): #All ZERO
         return 15
     elif (rem == 0 and sold1 == 0 and sold2 < 10): #ALL FOR ONE PRODUCT VALUE
         return sold2*3
     elif (rem == 0 and sold1 < 10 and sold2 ==0):
         return sold1*3
     elif (rem < 10 and sold1 == 0 and sold2 == 0):
         return rem*3
     #END FOR ONE PRODUCT VALUE
     elif (rem>= 10 and  sold1>=10 and sold2>=10):

          if((rem/3)>=(sold1+10) or (rem/3)>=(sold1+10)):
              return 0
          else:
              return calculate(rem,sold1,sold2)-rem
     elif (rem<10 and sold1<10 and sold2<10):
         return calculate(rem,sold1,sold2)
     elif (rem == 0 and sold1>=10 and sold2>=10):
         return calculate(rem,sold1,sold2)
     else:
         return sold1






@app.route('/forecaster', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        # show html form
        return '''
            <form method="post">

        <h3>Type in the remaining stocks: </h3>        <input type="text" name="remaining" />
<br/>
        <h3>Type in the stocks for the past month: </h3>        <input type="text" name="sold1" />
<br/>
       <h3>Type in the stocks for the the month before the past month: </h3>         <input type="text" name="sold2" />
<br/>
<br/>
                <input type="submit" value="forecast" />
            </form>
        '''
    elif request.method == 'POST':
        # calculate result
        rem = int(request.form.get('remaining'))
        sold1 = int(request.form.get('sold1'))
        sold2 = int(request.form.get('sold2'))

        result = forecast(rem,sold1,sold2)

        return '<h1>Result: %s</h1>' % result

at forecastvalues() i wanted to evaluate the values on each row of the csv and evaluate each of those values using the forecast() and put the result of the evaluation in the 4th column of each row.

So there I looped it. and took the values turned them into integers, assigned them to the variables rem, sold1, and sold2, and plugged them in the forecast(rem, sold1, sold2) . And then I assigned the return value of forecast to result, and put it in the loop so that it could be assigned to the 4th column of the row. I imagine the output to be like this:

From these input

1 2 1
1 3 1
1 2 2

to this output when the program is done with the file

1 2 1 result
1 3 1 result
1 2 2 result

But it seems to have no effect on the csv file? I wrote the name of the test csv as the filename so that I could test it. IS there something wrong in my pandas functions? or have i implemented it the wrong way? I used the cheatsheet for pandas in making the code.

You are calling pd.to_csv('test.csv') , but I do not believe this will work as there is no pandas.to_csv method. There is however a pandas.DataFrame.to_csv method, which will do what you are trying to accomplish. You need to call

records.to_csv('test.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM