【问题标题】:Handle nested lists in pandas处理 pandas 中的嵌套列表
【发布时间】:2020-01-22 19:36:00
【问题描述】:

如何在 Python 中将包含 dict 的嵌套列表转换为数据框中的额外列?

我从 API 接收到字典中的信息,

{'orders': 
[
{   'orderId': '2838168630', 
    'dateTimeOrderPlaced': '2020-01-22T18:37:29+01:00', 
    'orderItems': [{    'orderItemId':  'BFC0000361764421', 
                        'ean': '234234234234234', 
                        'cancelRequest': False, 
                        'quantity': 1}
                        ]}, 

{   'orderId': '2708182540', 
    'dateTimeOrderPlaced': '2020-01-22T17:45:36+01:00', 
    'orderItems': [{    'orderItemId':  'BFC0000361749496', 
                        'ean': '234234234234234', 
                        'cancelRequest': False, 
                        'quantity': 3}
                        ]}, 

{   'orderId': '2490844970', 
    'dateTimeOrderPlaced': '2019-08-17T14:21:46+02:00', 
    'orderItems': [{    'orderItemId': 'BFC0000287505870', 
                        'ean': '234234234234234', 
                        'cancelRequest': True, 
                        'quantity': 1}
                        ]}

通过这样做,我设法将其变成了一个简单的数据框:

pd.DataFrame(recieved_data.get('orders'))

输出:

orderId    date    oderItems
1          1-12    [{orderItemId: 'dfs13', 'ean': '34234'}]
2          etc.
...

我想要这样的东西

orderId    date    oderItemId    ean
1          1-12    dfs13         34234
2          etc.
...

我已经尝试使用 Iloc 单独列出 orderItems 列,然后将其转换为列表,以便我可以再次尝试提取值。但是,我仍然得到一个列表,我需要从中提取另一个列表,其中包含字典。

【问题讨论】:

  • 为什么不将其全部取消嵌套,然后再将其放入数据框中?
  • 我在早期也尝试过使用 json_normalize 方法,但是当我尝试使用的数据是 dict 时收到错误消息,因此我继续尝试使用 dicts 查找方法。也许我做错了什么
  • 请按收到的数据发布。这应该可以解决它:stackoverflow.com/questions/55679381/…

标签: python pandas


【解决方案1】:
# Load the dataframe as you have already done.

temp_df = df['orderItems'].apply(pd.Series)

# concat the temp_df and original df

final_df = pd.concat([df, temp_df])

# drop columns if required

希望它对你有用。

干杯

【讨论】:

    【解决方案2】:

    通过结合这个问题的答案,我达到了我的最终目标。我编辑了以下内容:

    #unlist the orderItems column
    temp_df = df['orderItems'].apply(pd.Series)
    
    #Put items in orderItems into seperate columns
    temp_df_json = json_normalize(temp_df[0])
    
    #Join the tables
    final_df = df.join(temp_df_json)
    
    #Drop the old orderItems coloumn for a clean table
    final_df = final_df.drop(["orderItems"], axis=1)
    

    另外,我使用 .join() 代替 .concat() 根据现有索引连接两个表。

    【讨论】:

      【解决方案3】:

      为了清楚起见,您从 API 接收到一个 json,因此您可以尝试使用函数json_normalize。 试试这个:

      import pandas as pd
      from pandas.io.json import json_normalize
      # DataFrame initialization
      df = pd.DataFrame({"orderId": [1], "date": ["1-12"], "oderItems": [{ 'orderItemId': 'dfs13', 'ean': '34234'}]})
      
      # Serializing inner dict
      sub_df = json_normalize(df["oderItems"])
      
      # Dropping the unserialized column
      df = df.drop(["oderItems"], axis=1)
      
      # joining both dataframes.
      df.join(sub_df)
      

      所以输出是:

          orderId date    ean     orderItemId
      0   1       1-12    34234   dfs13
      

      【讨论】:

      • 谢谢!当我使用您的代码时,我得到相同的输出。但是,当我尝试使用从 API 接收的数据时,我收到以下错误:'list' object has no attribute 'values'
      • @NielsvanLeeuwen 始终分享整个错误消息。
      • AttributeError Traceback(最近一次调用最后一次)----> 5 sub_df = json_normalize(df["orderItems"]) ~/opt/anaconda3/lib/python3.7/site-packages/pandas /io/json/_normalize.py in (.0 --> 258 if any([isinstance(x, dict) for x in y.values()] for y in data): AttributeError: 'list' object没有属性“值”
      • 我相信这是因为 orderItems 中的字典被放置在列表中。这也是我最初问的问题,如何将带有 dict 的嵌套列表转换为数据框。
      猜你喜欢
      • 2014-04-15
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 2018-11-01
      • 2020-01-04
      • 1970-01-01
      相关资源
      最近更新 更多