我写了像这样的代码:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.pro-football-reference.com/teams/nwe/2013_injuries.htm'
# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# html parsing
page_soup = soup(page_html, "html.parser")
containers = page_soup.find("tbody")
head = page_soup.find("thead")
player = containers.find_all("tr")
weeks = head.find_all('th')
week_list = [i['data-stat'] for i in weeks][1:]
for week in week_list:
for tr in player:
th = tr.find_all("th")
name = [i.text for i in th]
td = tr.find('td', {'data-stat':week})
week = td["data-stat"]
try:
injury = td["data-tip"]
print([name, injury, week])
except KeyError:
injury = "NA"
print([name, injury, week])
我得到的输出是:
,即所有数据均按列显示。但是我想按行显示数据。即每个条目分别
like;
import pandas as pd
import numpy as np
import json
from flask import Flask,request,jsonify
app = Flask(__name__)
@app.route('/df',methods=['POST','GET'])
def ff():
df = pd.read_csv(r'dataframe_post.csv')
row = [5, 'Sanjeev', 'AE']
df.loc[len(df)] = row
# print(dfs)
ls=list(df.to_dict().values())
return jsonify(ls)
if __name__ == '__main__':
app.run(debug=True)
,依此类推。
答案 0 :(得分:1)
在您的df.to_dict
调用中,使用to_dict(orient='records')
将按行构建json
答案 1 :(得分:1)
要以所需的格式返回json,可以使用内置的dataframe方法,而不是列出并进行jsonifying:
df.to_json(orient="records")
这将为您提供一个json编码的字符串,如下例所示:
df = pd.DataFrame([[5, 'Sanjeev', 'AE'], [6, 'Sven', 'AA']], columns = ["id", "name", "2"])
哪个返回:
id name 2
0 5 Sanjeev AE
1 6 Sven AA
然后作为JSON:
df.to_json(orient="records")
'[{"id":5,"name":"Sanjeev","2":"AE"},{"id":6,"name":"Sven","2":"AA"}]'