我使用的是python2.7和pandas 0.11.0.
我尝试使用DataFrame.apply(func)填充数据框的列.func()函数应该返回一个numpy数组(1x3).
import pandas as pd
import numpy as np
df= pd.DataFrame(np.random.randn(4, 3), columns=list('ABC'))
print(df)
A B C
0 0.910142 0.788300 0.114164
1 -0.603282 -0.625895 2.843130
2 1.823752 -0.091736 -0.107781
3 0.447743 -0.163605 0.514052
Run Code Online (Sandbox Code Playgroud)
用于测试目的的功能:
def test(row):
# some complex calc here
# based on the values from different columns
return np.array((1,2,3))
df['D'] = df.apply(test, axis=1)
[...]
ValueError: Wrong number of items passed 1, indices imply 3
Run Code Online (Sandbox Code Playgroud)
有趣的是,当我从头开始创建数据框时,它工作得很好,并按预期返回:
dic = {'A': {0: 0.9, 1: -0.6, 2: 1.8, 3: 0.4}, …Run Code Online (Sandbox Code Playgroud) 我的目标是为我的Web应用程序提供REST API.使用:
我需要保护对Web和REST访问的数据的访问.但是,request在尝试连接到安全API时,我无法获得任何常规python 成功.
使用本问题末尾提供的全功能模块获得以下输出.
我设法在使用时得到正确的答案http://127.0.0.1:5000/api/v1/free_stuff:
>>> import requests
>>> r=requests.get('http://127.0.0.1:5000/api/v1/free_stuff')
>>> print 'status:', r.status_code
status: 200 # all is fine
Run Code Online (Sandbox Code Playgroud)
尝试使用身份验证时http://127.0.0.1:5000/api/v1/protected_stuff:
>>> from requests.auth import HTTPBasicAuth, HTTPDigestAuth
>>> r=requests.get('http://127.0.0.1:5000/api/v1/protected_stuff',
auth=HTTPBasicAuth('test', 'test')) # the same with ``HTTPDigestAuth``
>>> print 'status:', r.status_code
status: 401
>>> r.json() # failed!
{u'message': u'401: Unauthorized'}
Run Code Online (Sandbox Code Playgroud)
这是一个用于产生上述结果的虚拟功能模块:
from flask import Flask, render_template, url_for, redirect
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, …Run Code Online (Sandbox Code Playgroud) python restful-authentication flask flask-security flask-restless
我目前使用flask、sqlalchemy 和jinja2 构建一个Web 应用程序。
为了获得合适的 Web 界面,我按如下方式构建视图:
@app.route('/mydata/', methods=['GET'])
@login_required
def mydata_list():
# build data here...
return render_template('mydata/index.html', data=data))
Run Code Online (Sandbox Code Playgroud)
现在,如果我需要构建一个 REST API,我应该以
return jsonify(data)
Run Code Online (Sandbox Code Playgroud)
那么,如何处理这个以避免代码重复呢??api=True在我的 url 中添加一个,在我的视图中测试它,然后返回适当的答案是一个好习惯吗?