处理熊猫中的嵌套列表

时间:2020-01-22 19:36:00

标签: python pandas

如何在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列,然后将其变成一个列表,这样我就可以尝试再次提取值。但是我最终还是得到一个列表,我需要从中提取另一个列表,其中包含字典。

3 个答案:

答案 0 :(得分: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

希望它对您有用。

欢呼

答案 1 :(得分:0)

为了清楚起见,您正在从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

答案 2 :(得分:0)

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

#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()来基于现有索引连接两个表。