展开pandas dataframe列中字典的嵌套列表

2024-04-26 11:56:24 发布

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

我有一个名为“leads”的数据帧,它是从将sfdcsoql的输出保存到数据帧中得到的。我一直在尝试扩展“潜在客户记录”一栏

Company    Month     Amount   Leads__r.done   Leads__r.record                      Leads__r.totalSize
0   A1  September   500000    True          [{u'Id': u'Q500, u'Company': u'...                1.0
1   B1  December    16200     True          [{u'Id': u'Q600', u'Company': u'...               1.0
2   C1  December    35000     True          [{u'Id': u'Q700', u'Company': u'...               1.0
3   D1  December    16200     True          [{u'Id': u'Q800', u'Company': u'...               1.0
4   E1  December    40000     True          [{u'Id': u'Q900', u'Company': u'...               1.0
5   F1  December    54000     True          [{u'Id': u'Q950', u'Company': u'...               1.0
6   G1  August      67700     True          [{u'Id': u'Q1000', u'Company': u'...              1.0

这是leads['leads\uu r.record']的输出:

^{pr2}$

引线输出['leads\uu r.record'][0]

[{u'Company': u'A1',
  u'CurrencyIsoCode': u'AUD',
  u'Date_Submitted__c': u'2018-09-12',
  u'Deal_Amount__c': 500000,
  u'Id': u'Q500',
  u'DEAL_ID': u'a78989',
  u'PrimaryProductFamily__c': u'Cloud',
  u'Primary_Product_Family__c': u'Cloud',
  u'Product_interest__c': None,
  u'attributes': {u'type': u'Lead',
  u'url': u'/services/data/v24.0/sobjects/Lead/00Qf200001Zls5CEAR'}}]

我什么都试过了,:

pd.concat([pd.DataFrame(x) for x in leads['Leads__r.record']], 
    keys=leads['Leads__r.totalSize']).reset_index(level=1, drop=True).reset_index()

上面的方法是可以的,但是由于某些原因我一直得到错误,ValueError:DataFrame构造函数调用不正确!在

leads['Leads__r.records'].reset_index().drop('index',1)

这是我最近来的一次:

pd.concat([pd.DataFrame(x) for x in leads['Leads__r.records'][0:200]], keys=leads.index).reset_index(level=1, drop=True).reset_index()

这是有效的,但仅适用于前200行


Tags: 数据idtruedataframeindexrecordamountcompany
1条回答
网友
1楼 · 发布于 2024-04-26 11:56:24

尝试json_normalize如下:

from pandas.io.json import json_normalize

# Convert the column of single-element lists to a list of dicts
records = [x[0] for x in df['Leads__r.record']]

# normalize the records and concat with the original df
res = pd.concat([df.drop('Leads__r.record', axis=1), json_normalize(records)], axis=1)

相关问题 更多 >