python - 基于列的字符串到熊猫数据框
问题描述
我正在向烧瓶服务器 ( http://localhost:5000/req/?q=139,2,10,60,5,1462,7,5,6,9,17,78
) 发送一个 ajax GET 请求,以便检索一些值并将它们分配给 Dataframe。手动操作,效果很好:
df = pd.DataFrame(data=[[139,2,10,60,5,1462,7,5,6,9,17,78]],columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])
但我需要通过 ajax 来自request.args的数字,然后作为数组基于 Dataframe。
@app.route('/req/', methods=['GET'])
def foo():
args = dict(request.args.to_dict())
t = request.args["q"]
return getResults(t), 200
getResults() 类似于:
def getResults(name):
df = pd.DataFrame(data=[[name]], columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])
""""
但这当然行不通。给出错误:ValueError: 12 列已通过,传递的数据有 1 列
我怎样才能做到这一点 ?我试过拆分字符串,尝试转换为数组..没有任何效果。
解决方案
args 被解析为字符串,因此在t = request.args["q"]
, t
is之后"139,2,10,60,5,1462,7,5,6,9,17,78"
,您需要一个 int 列表
@app.route('/req') # GET only is default method
def foo():
t = request.args["q"]
t = [int(val) for val in t.split(",")]
return getResults(t) # 200 is the default status code
和
def getResults(name):
df = pd.DataFrame(data=[name], # no extra []
Also prefer /req
(that allows both with and without trailing slash) rather than /req/
that accept only one , refer to this for detail
推荐阅读
- ios - Flutter - IAP 项目在应用程序中不起作用
- python - Python - 应用函数以每两个单词分隔列中的字符串
- kubernetes - Docker 桌面上的 Kubernetes 仪表板和入口
- c# - 我的控制器无法在生产中保存物理文件路径
- python - 使用 eval(*code*) 和只使用 *code* 有什么区别?
- cad - CATIA 生成形状设计中的形状圆角错误
- video - 使用 ffmpeg 转换大型视频文件
- php - 如何在一个数组中保存和打印多个mysql表中的选定结果?
- qemu - QEMU 中的 Smbus 设备仿真
- python - 如何在 pyqt5 中的 QWebEngineView 上绘画