我有一个以这种形式输出的字典:
response['candles'][0:2]
[{'complete': True,
'mid': {'c': '0.91535', 'h': '0.91535', 'l': '0.91535', 'o': '0.91535'},
'time': '2002-05-06T21:00:00.000000000Z',
'volume': 1},
{'complete': True,
'mid': {'c': '0.90435', 'h': '0.90435', 'l': '0.90435', 'o': '0.90435'},
'time': '2002-05-07T21:00:00.000000000Z',
'volume': 1}]
我可以轻松地创建一个如下所示的DataFrame:
res = pd.DataFrame(response['candles'])
complete mid time volume
0 True {'o': '0.91535', 'h': '0.91535', 'l': '0.91535... 2002-05-06T21:00:00.000000000Z 1
1 True {'o': '0.90435', 'h': '0.90435', 'l': '0.90435... 2002-05-07T21:00:00.000000000Z 1
我可以访问“ mid”字典项,如下所示:
response['candles'][0]['mid']['c']
'0.91535'
但是,如何在DataFrame中为每个“中间”项目添加列,而不是在DataFrame中添加字典?我想要一列['mid'] ['o'],['mid'] ['h']等。
谢谢
用途pandas.io.json.json_normalize
:
d = [{'complete': True,
'mid': {'c': '0.91535', 'h': '0.91535', 'l': '0.91535', 'o': '0.91535'},
'time': '2002-05-06T21:00:00.000000000Z',
'volume': 1},
{'complete': True,
'mid': {'c': '0.90435', 'h': '0.90435', 'l': '0.90435', 'o': '0.90435'},
'time': '2002-05-07T21:00:00.000000000Z',
'volume': 1}]
pd.io.json.json_normalize(d)
#complete mid.c mid.h mid.l mid.o time volume
#0 True 0.91535 0.91535 0.91535 0.91535 2002-05-06T21:00:00.000000000Z 1
#1 True 0.90435 0.90435 0.90435 0.90435 2002-05-07T21:00:00.000000000Z 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句