简体   繁体   English

Python使用熊猫评估图纸上的值,然后在文件上写入

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

Hello I'm new to web app dev. 您好,我是Web应用程序开发人员的新手。 I'm trying to make an app, which manipulates a csv file. 我正在尝试制作一个可处理csv文件的应用程序。

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. 在Forecastvalues()处,我想评估csv每一行的值,并使用Forecast()评估每个值,并将评估结果放在每一行的第四列。

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) . 然后将这些值转换为整数,将它们分配给变量rem,sell1和sold2,然后将它们插入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? 但这似乎对csv文件没有影响? I wrote the name of the test csv as the filename so that I could test it. 我将测试csv的名称写为文件名,以便可以对其进行测试。 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. 您正在调用pd.to_csv('test.csv') ,但由于没有pandas.to_csv方法,因此我认为这不会起作用。 There is however a pandas.DataFrame.to_csv method, which will do what you are trying to accomplish. 但是,有一个pandas.DataFrame.to_csv方法,它将执行您要完成的工作。 You need to call 你需要打电话

records.to_csv('test.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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