如何在Pandas中左连接DataFrame并生成JSON格式新列
解决方案:Pandas按卖家左连接并生成JSON格式商品列
步骤说明
- 对商品信息DataFrame按
seller分组,将每组商品详情转换为标准JSON数组格式 - 将分组结果与卖家信息DataFrame做左连接,确保所有卖家信息完整保留
完整代码示例
import pandas as pd import json # 初始化卖家信息DataFrame df_sellers = pd.DataFrame({ 'seller': ['smith', 'john', 'alan'], 'sales': ['Yes', 'No', 'Yes'], 'is_active': ['Yes', 'Yes', 'No'] }) # 初始化商品信息DataFrame df_products = pd.DataFrame({ 'seller': ['smith', 'smith', 'smith', 'john', 'john', 'john', 'alan', 'alan', 'alan'], 'product': ['book', 'dvd', 'cd', 'sofa', 'umbrella', 'bag', 'tv', 'cable', 'fridge'], 'EAN': ['ANUDH17e89', 'NVGS5w621', 'NCYbh658', 'codkv32876', 'chudbic132', 'coGTTf276', 'BYU1890H', 'ndhnjh0988', 'BTFS$42561'], 'URL': ['www.ecvdgv.com', 'www.awfcj.com', 'www.bstx.com', 'www.....', 'www.....', 'www.....', 'www.....', 'www.....', 'www.....'], 'PRICE': [13.45, 23.76, 9.99, 348, 38, 54, 239, 5, 158] }) # 分组生成JSON格式的商品列 product_json = df_products.groupby('seller').apply( lambda group: json.dumps( group.drop('seller', axis=1).to_dict('records'), indent=2 # 缩进格式化,提升JSON可读性 ) ).reset_index(name='New_column') # 左连接两个DataFrame final_df = df_sellers.merge(product_json, on='seller', how='left') # 查看结果 print(final_df)
代码解释
groupby('seller'):按卖家维度聚合商品数据,确保同一卖家的商品被归为一组group.drop('seller', axis=1):移除分组后重复的seller字段,仅保留商品核心信息to_dict('records'):将每组商品数据转换为字典列表(每个字典对应一件商品的详情)json.dumps(..., indent=2):将字典列表转为格式化的JSON字符串,便于后续读取和使用merge(..., how='left'):左连接保证原卖家信息的所有行都被保留,避免遗漏无商品的卖家(示例中无此场景)
输出效果(简化展示)
seller sales is_active New_column 0 smith Yes Yes [ { "product": "book", "EAN": "ANUDH17e89", "URL": "www.ecvdgv.com", "PRICE": 13.45 }, { "product": "dvd", "EAN": "NVGS5w621", "URL": "www.awfcj.com", "PRICE": 23.76 }, ... ] 1 john No Yes [ { "product": "sofa", "EAN": "codkv32876", "URL": "www.....", "PRICE": 348 }, ... ] 2 alan Yes No [ { "product": "tv", "EAN": "BYU1890H", "URL": "www.....", "PRICE": 239 }, ... ]
内容的提问来源于stack exchange,提问作者Thomas Chenu
相关产品推荐
相关产品推荐

