how to upload csv data and then use the data for calculation

30 views
Skip to first unread message

wangfen...@gmail.com

unread,
Sep 18, 2017, 10:31:35 AM9/18/17
to web2py-users
I am a nood in coding and web development. I want to use web2py to establish a small APP for my research. But I have some problems to import the csv data and then use the data for calculation (or model establishment). I search for some examples in manual book, web2pyslices.com and some other websites, but still could not solve it.

Here is my controllers and views for my app

#controller data.py (import csv data which contains 3 columns salinity, N2 and chla)

def data(): 
import numpy as np
import pandas as pd
dat = pd.read_csv('C:\Users\wangfeng\Desktop\TEST.csv')
sal = dat['salinity']
N2 = dat['N2']
chl = dat['chla']
return dict(sal=sal, N2=N2, chl=chl)
# controller csv.py (creat a form to upload data, this code is copied from some other websites)

def import_table():
    form = SQLFORM.factory(Field('table',requires=IS_IN_SET(db.tables)),
                           Field('csvfile','upload',uploadfield=False))
    form.process()
    if form.accepted:
        try:
            db[form.vars.table].import_from_csv_file(request.vars.csvfile.file)
        except: form.errors.csvfile = 'invalid file'
    return dict(form = form)

#data/data.html (for calculation of my research)

#show the data
<h1>这是 This is raw data</h1>
<h5>sal={{=sal}}</h5>
<h5>N2={{=N2}}</h5>
<h5>chl={{=chl}}</h5>
{{import numpy as np}}
{{from scipy.optimize import leastsq}}
#calculation
#data standization
{{s_sal=((chl-np.mean(sal))/np.std(sal))}}
{{s_N2=((chl-np.mean(N2))/np.std(N2))}}
#model fitting
{{def func1(t,x,y):}}
    {{return 1/(t[0]+t[1]*np.exp(t[2]*x))-y}}
{{t0=np.array([1.0,1.0,1.0])}}

{{for i in np.arange(0,2.0,0.05):}}
    {{index = i*s_sal + (2-i)*s_N2}}
    {{cf = leastsq(func1,t0,args=(index,chl))}}
#show the results
<li>
"Model: "{{=i}}"*salinity+"{{=2-i}}"*N2" &nbsp;&nbsp; "Equation: 1/("{{=round(cf[0][0],2)}}"+"{{=round(cf[0][1],2)}}"*EXP("{{=round(cf[0][2],2)}}"*x))"
</li>
{{pass}}

Thanks all

TEST.csv
Reply all
Reply to author
Forward
0 new messages