Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从特定API(BLS)创建逗号分隔的数据表而不使用prettytable,如示例代码所示?_Python_Api - Fatal编程技术网

Python 从特定API(BLS)创建逗号分隔的数据表而不使用prettytable,如示例代码所示?

Python 从特定API(BLS)创建逗号分隔的数据表而不使用prettytable,如示例代码所示?,python,api,Python,Api,我正在学习使用劳工统计局的API从中提取数据。示例代码: import requests import json import prettytable headers = {'Content-type': 'application/json'} data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":&

我正在学习使用劳工统计局的API从中提取数据。示例代码:

import requests
import json
import prettytable
headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":"2014"})
p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
json_data = json.loads(p.text)
for series in json_data['Results']['series']:
    x=prettytable.PrettyTable(["series id","year","period","value","footnotes"])
    seriesId = series['seriesID']
    for item in series['data']:
        year = item['year']
        period = item['period']
        value = item['value']
        footnotes=""
        for footnote in item['footnotes']:
            if footnote:
                footnotes = footnotes + footnote['text'] + ','
       'if 'M01' <= period <= 'M12':'
            x.add_row([seriesId,year,period,value,footnotes[0:-1]])
    output = open(seriesId + '.txt','w')
    output.write (x.get_string())
    output.close()
导入请求
导入json
进口漂亮表
headers={'Content-type':'application/json'}
data=json.dumps({“seriesid”:['LAUMT421090000000005'],“startyear”:“2011”,“endyear”:“2014”})
p=请求。post('https://api.bls.gov/publicAPI/v2/timeseries/data/,数据=数据,标题=标题)
json_data=json.loads(p.text)
对于json_数据['Results']['series']中的系列:
x=prettytable.prettytable([“序列id”、“年份”、“期间”、“值”、“脚注”])
seriesId=系列['seriesId']
对于系列[“数据”]中的项目:
年份=项目[‘年份’]
期间=项目[“期间”]
值=项目[“值”]
脚注=“”
对于第[‘脚注’]项中的脚注:
如果脚注:
脚注=脚注+脚注['text']+','
'如果'M01'
在上述代码行之后,使用以下stackoverflow链接中描述的步骤进行后续步骤:


希望有帮助

在下面的代码中,我创建了一个数据帧,然后使用
pandas.dataframe.to_csv()
()将其输出到.csv文件。在本例中,我还添加了try和except子句,以在用户输入无效的序列ID(与本例不同)或用户超过BLS API的每日点击次数(未注册用户每天最多可请求25次查询)时引发异常

在本例中,我添加了一个列来显示SeriesID,如果SeriesID列表包含多个项,这将证明它更有用,并有助于区分不同的系列。我还对脚注列进行了一些额外的操作,使其在输出的数据帧中更有意义

import pandas as pd
import json
import requests

headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":"2014"})
p = requests.post('https://api.bls.gov/publicAPI/v1/timeseries/data/', data=data, headers=headers)
json_data = json.loads(p.text)
try:
    df = pd.DataFrame()
    for series in json_data['Results']['series']:
        df_initial = pd.DataFrame(series)
        series_col = df_initial['seriesID'][0]
        for i in range(0, len(df_initial) - 1):
            df_row = pd.DataFrame(df_initial['data'][i])
            df_row['seriesID'] = series_col
            if 'code' not in str(df_row['footnotes']): 
                df_row['footnotes'] = ''
            else:
                df_row['footnotes'] = str(df_row['footnotes']).split("'code': '",1)[1][:1]
            df = df.append(df_row, ignore_index=True)
    df.to_csv('blsdata.csv', index=False)
except:
    json_data['status'] == 'REQUEST_NOT_PROCESSED'
    print('BLS API has given the following Response:', json_data['status'])
    print('Reason:', json_data['message'])
如果要输出.xlsx文件而不是.csv文件,只需将
df.to_csv('blsdata.csv',index=False)
替换为
df.to_excel('blsdata.xlsx',index=False,engine='xlsxwriter')

预期输出的.csv文件:

如果使用
pandas.DataFrame.to_excel()
而不是
pandas.DataFrame.to_csv()
,则应输出.xlsx文件:


这是一个多么惊人的答案。对不起,我花了这么长时间才回复。这个问题直到今天才在工作中出现。我通过胡闹和试着一块一块地理解你的代码学到了很多东西,比如
len(df)
try except
。结果只有两个小问题:1。结果不包括年初的第一个月。我将尝试对范围内的I使用
(0,len(df_initial)):
。2.我的结果表中的脚注列为空。但这些都是小事。我学习了循环的
和熊猫的
,但从未将它们组合在一起。你在这里所做的真的让我大开眼界。非常感谢你。我在哪里可以读到更多关于这样的东西:不仅使用pandas做我通常在Excel中做的事情,而且还将它与Python基础知识相结合。在本例中,您如何知道json_数据中有哪些列?谢谢。我对json数据一无所知,所以我也想知道'df_initial=pd.DataFrame(series)`如何工作。我试图返回
json_数据['Results']['series']
,以查看它由什么组成,但返回的结果似乎与
json_数据一样
import pandas as pd
import json
import requests

headers = {'Content-type': 'application/json'}
data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":"2014"})
p = requests.post('https://api.bls.gov/publicAPI/v1/timeseries/data/', data=data, headers=headers)
json_data = json.loads(p.text)
try:
    df = pd.DataFrame()
    for series in json_data['Results']['series']:
        df_initial = pd.DataFrame(series)
        series_col = df_initial['seriesID'][0]
        for i in range(0, len(df_initial) - 1):
            df_row = pd.DataFrame(df_initial['data'][i])
            df_row['seriesID'] = series_col
            if 'code' not in str(df_row['footnotes']): 
                df_row['footnotes'] = ''
            else:
                df_row['footnotes'] = str(df_row['footnotes']).split("'code': '",1)[1][:1]
            df = df.append(df_row, ignore_index=True)
    df.to_csv('blsdata.csv', index=False)
except:
    json_data['status'] == 'REQUEST_NOT_PROCESSED'
    print('BLS API has given the following Response:', json_data['status'])
    print('Reason:', json_data['message'])