正在尝试展开列中的嵌套词典列表

2024-05-19 19:17:53 发布

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

我正在尝试扩展dataframe中的列“Records”,它是一个嵌套的字典列表 我正在尝试提取列: 产品,利息,身份证,公司,交易,日期,家庭,金额,货币

 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:DataFrame构造函数没有正确调用!你知道吗

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

Tags: noneidsizedateproductfamilyamountcompany
1条回答
网友
1楼 · 发布于 2024-05-19 19:17:53

您可以使用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以获得最终所需的输出数据帧。你知道吗

相关问题 更多 >