有选择地将JSON数据加载到datafram中

2024-10-03 17:22:32 发布

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

我有一些json数据,我想把它们放到pandas数据框中。json如下所示:

{'date': [20170629,
  20170630,
  20170703,
  20170705,
  20170706,
  20170707],
 'errorMessage': None,
 'seriesarr': [{'chartOnlyFlag': 'false',
   'dqMaxValidStr': None,
   'expression': 'DB(FXO,V1,EUR,USD,7D,VOL)',
   'freq': None,
   'frequency': None,
   'iDailyDates': None,
   'label': '',
   'message': None,
   'plotPoints': [0.0481411225888,
    0.0462401214563,
    0.0587196848727,
    0.0765737640932,
    0.0678912611279,
    0.0675766942022],
   }

我试图创建一个pandas数据帧,其中'date'作为索引,'plotPoints'作为第二列。我不需要任何其他信息。在

我试过了

df = pd.io.json.json_normalize(data, record_path = 'date', meta = ['seriesarr', ['plotPoints']])

当我这样做时,我得到以下错误:

^{pr2}$

如有任何帮助,我们将不胜感激。在

谢谢!在


Tags: 数据nonejsonfalsepandasdbdatev1
2条回答

正如@COLDSPEED所指出的,直接从字典列中获取数据是合适的,因为'plotPoints'包含在dict列表中

列表理解变体如下所示,其中日期为索引,plotpoints为列。。在

col1 = data['date']
adict = dict((k,v)  for d in data['seriesarr'] for k,v in d.iteritems() )
col2 = adict['plotPoints']
pd.DataFrame(data= col2, index=col1)

>>>              0
20170629  0.048141
20170630  0.046240
20170703  0.058720
20170705  0.076574
20170706  0.067891
20170707  0.067577

IIUC,json_normalize在这里可能帮不了你。取而代之的是,提取数据然后直接将其加载到数据帧中可能更容易。如果需要,请使用pd.to_datetime转换为datetime

date = data.get('date')
plotPoints = data.get('seriesarr')[0].get('plotPoints')

df = pd.DataFrame({'date' : pd.to_datetime(date, format='%Y%m%d'),
                   'plotPoints' : plotPoints})
df
        date  plotPoints
0 2017-06-29    0.048141
1 2017-06-30    0.046240
2 2017-07-03    0.058720
3 2017-07-05    0.076574
4 2017-07-06    0.067891
5 2017-07-07    0.067577

假设您的数据与问题中显示的数据完全一致。

相关问题 更多 >