首页 > 解决方案 > 用熊猫创建嵌套对象

问题描述

我有一个看起来像这样的输入 DataFrame 在此处输入图像描述

input_data = {
    'url1': ['https://my-website.com/product1', 'https://my-website.com/product1', 'https://my-website.com/product2', 'https://my-website.com/product2'],
    'url2': ['https://not-my-website.com/product1', 'https://not-my-website.com/product1', 'https://not-my-website.com/product2', 'https://not-my-website.com/product2'],
    'size': ['S', 'L', 'S', 'L'],
    'used_price': [100, 110, 210, 220],
    'new_price': [1000, 1100, 2100, 2200],
    }

input_df = pd.DataFrame(data=input_data)

我想把它变成这样的东西 在此处输入图像描述

output_data = {
    'url1': ['https://my-website.com/product1', 'https://my-website.com/product2'],
    'url2': ['https://not-my-website.com/product1', 'https://not-my-website.com/product2'],
    'target': [
        {
            'S': {'used_price': 100, 'new_price': 1000}, 
            'L': {'used_price': 120, 'new_price': 1200}
        },
        {
            'S': {'used_price': 200, 'new_price': 2000}, 
            'L': {'used_price': 220, 'new_price': 2200}
        }
    ]
}

output_df = pd.DataFrame(data=output_data)

标签: pandas

解决方案


您可以使用groupbyapply

(input_df.groupby(['url1', 'url2'])[['size', 'used_price', 'new_price']]
         .apply(lambda d: d.set_index('size').T.to_dict())
         .rename('target')
         .reset_index()
)

输出:

                              url1                                 url2                                                                                      target
0  https://my-website.com/product1  https://not-my-website.com/product1  {'S': {'used_price': 100, 'new_price': 1000}, 'L': {'used_price': 110, 'new_price': 1100}}
1  https://my-website.com/product2  https://not-my-website.com/product2  {'S': {'used_price': 210, 'new_price': 2100}, 'L': {'used_price': 220, 'new_price': 2200}}

推荐阅读