试图扩大在列词典的嵌套列表

问题描述 投票:0回答:1

我想扩大我的数据框列“史记”,也就是字典我想提取的列的嵌套列表:产品,兴趣,ID,公司,交易,日期,家庭,金额,币种

 Size                      Records.id


 10    [{u'Product': u'Ops', u'interest': 
      None, u'Id': u'78827dhdgsg', u'Company': u'Panda', 
      u'attributes': {u'type': u'Lead', u'url': 
      u'x567'}, 
      u'Deal': u'xxx6787', u'Date': 
      u'2018-12-03', u'Family': u'Ops', 
      u'Amount': 9300, u'Currency': u'USD'}]

         [{u'Product': u'gold', 
  5    u'interest': None, u'Id': u'377ffh38', 
      u'Company': u'BIGPT', u'attributes': {u'type': u'Lead', u'url': 
      u'x57589'}, 
      u'Deal': u'wakft', u'Date': 
      u'2015-10-17', u'Family': u'bugs', 
      u'Amount': 48889, u'Currency': u'USD'}]

我试过了

pd.concat([pd.DataFrame(x) for x in data['Records.id']],keys=data.index).reset_index(level=1,drop=True)

这用来工作,但由于某种原因,我不断收到错误,ValueError异常:数据帧的构造函数没有正确叫!

Size Product Interest Id   Company  Deal  Date     Family  Amount Currency

10   Ops             7882.. Panda xxx.. 2018-12-03   Ops     9300  USD 
5    Ops             377ff..BIGPT wakft 2015-10-17   Bugs   48889  USD
python pandas list dataframe nested
1个回答
1
投票

您可以使用stack

df_1 = (df.set_index('Size')['Records.id']
          .apply(pd.Series).stack()
          .apply(pd.Series).reset_index().drop('level_1',1))

你也可以这样做

df_2 = pd.concat([pd.DataFrame(x) for x in df['records id']], 
        keys=df['size']).reset_index(level=1, drop=True).reset_index()

但是,你需要加入size列本df_2得到最终所需的输出数据帧。

© www.soinside.com 2019 - 2024. All rights reserved.