将数据从api保存到dataframe

2024-10-02 18:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我从API获得以下输出:

[{'Chapters': {'id': book, 'name': firstbook'}, 'periodPrices': [{'reportDate': '2021-06-01T15:28:00', 'term': '3Q21', 'price': 10.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '4Q21', 'price': 10.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '1Q22', 'price': 10.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '2Q22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '3Q22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '4Q22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '1Q23', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '2Q23', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '2H21', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '1H22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '2H22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': '1H23', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': 'Cal 22', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': 'Cal 23', 'price': 0.0}, {'reportDate': '2021-06-01T15:28:00', 'term': 'Cal 24', 'price': 0.0}]}]

我试图在数据帧中获得以下输出:

 Date                     id               Term            price      
2021- 06-01T00:00:00      book             3Q21             10.0
2021-06-01T00:00:00       book             4Q21             10.0
2021-06-01T00:00:00       book             1Q22             10.5
etc

我尝试了以下代码:

l=parsed ###this is the output from API 
df=pd.DataFrame()
for i in l:
   d1 = {}
   reportDate = []
    price = []
 for j in i['Chapters']:
     reportDate.append(j['Date'])
     price.append(j['price'])
 d1['Date'] = reportDate
 d1['Rate'] = price
 df = df.append(pd.DataFrame(d1))
 df['Date'] = pd.to_datetime(df['Date'])

但是,我得到了以下错误:行for j in i['Chapters']:的字符串索引必须是整数


Tags: inapiiddffordatepricecal
3条回答

我看不出id列需要做什么。 因此,看看您是否可以使用此功能:

df = pd.DataFrame(l[0]["periodPrices"])
>>> df
             reportDate    term  price
0   2021-06-01T15:28:00    3Q21   10.0
1   2021-06-01T15:28:00    4Q21   10.0
2   2021-06-01T15:28:00    1Q22   10.0
3   2021-06-01T15:28:00    2Q22    0.0
4   2021-06-01T15:28:00    3Q22    0.0
5   2021-06-01T15:28:00    4Q22    0.0
6   2021-06-01T15:28:00    1Q23    0.0

您可以使用l[0]访问主dict。 然后使用l[0]['periodPrices']访问dict期间价格

如果需要id列,可以添加以下行:

df["id"] = l[0]["Chapters"]["id"]

您可以使用两行代码来完成此操作

df = pd.DataFrame(l[0]["periodPrices"])
df["id"] = l[0]["Chapters"]["id"]

因为DataFrame方法非常强大

l = data  ###this is the output from API
df = pd.DataFrame()
for i in l:
    d1 = {}
    reportDate = []
    price = []
for j in i['periodPrices']: # error here
    reportDate.append(j['reportDate']) # error here
    price.append(j['price'])
d1['Date'] = reportDate
d1['Rate'] = price
df = df.append(pd.DataFrame(d1))
df['Date'] = pd.to_datetime(df['Date'])

相关问题 更多 >