处理Pandas中的嵌套列表

2024-09-28 13:06:53 发布

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

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

我从API的dict中收到信息

{'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列,然后将其转换为一个列表,这样我就可以再次尝试提取值。然而,我最终还是得到了一个列表,我需要从中提取另一个列表,其中包含dict


Tags: 数据false列表dateetceandictquantity
3条回答
# 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

希望对你有用

干杯

通过综合这个问题的答案,我达到了我的最终目标。我认为:

#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)

另外,我没有使用.concat(),而是使用.join()基于现有索引连接两个表

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

相关问题 更多 >

    热门问题