我从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']:
的字符串索引必须是整数
我看不出
id
列需要做什么。 因此,看看您是否可以使用此功能:您可以使用
l[0]
访问主dict
。 然后使用l[0]['periodPrices']
访问dict
期间价格如果需要
id
列,可以添加以下行:您可以使用两行代码来完成此操作
因为DataFrame方法非常强大
相关问题 更多 >
编程相关推荐