基于模式分组列的PySpark实现:将价格数量列转为字典数组
DataFrame列重组为字典数组
问题描述
需要将输入DataFrame中的price_n和qty_n列按数字后缀分组,转换为包含price、qty、comments字段的字典数组,最终生成新的price_range列。
输入DataFrame
| item_name | price_1 | qty_1 | price_2 | qty_2 | price_3 | qty_3 | url |
|---|---|---|---|---|---|---|---|
| Samsung Z | 10000 | 5 | 9000 | 10 | 7000 | 20 | amazon.com |
| Moto G4 | 12000 | 10 | 10000 | 20 | 6000 | 50 | ebay.com |
| Mi 4i | 15000 | 8 | 12000 | 20 | 10000 | 25 | deals.com |
| Moto G3 | 20000 | 5 | 18000 | 12 | 15000 | 30 | ebay.com |
期望输出DataFrame
| item_name | price_range | url |
|---|---|---|
| Samsung Z | [{price:10000,qty:5, comments:""},{price:9000,qty:10, comments:""},{price:7000,qty:20, comments:""}] | amazon.com |
| Moto G4 | [{price:12000,qty:10, comments:""},{price:10000,qty:20, comments:""},{price:6000,qty:50, comments:""}] | ebay.com |
| Mi 4i | [{price:15000,qty:8, comments:""},{price:12000,qty:20, comments:""},{price:10000,qty:25, comments:""}] | deals.com |
| Moto G3 | [{price:20000,qty:5, comments:""},{price:18000,qty:12, comments:""},{price:15000,qty:30, comments:""}] | ebay.com |
解决方案(Python Pandas)
通过列名拆分+分组聚合的方式实现,具体代码如下:
import pandas as pd # 构造输入DataFrame df = pd.DataFrame({ 'item_name': ['Samsung Z', 'Moto G4', 'Mi 4i', 'Moto G3'], 'price_1': [10000, 12000, 15000, 20000], 'qty_1': [5, 10, 8, 5], 'price_2': [9000, 10000, 12000, 18000], 'qty_2': [10, 20, 20, 12], 'price_3': [7000, 6000, 10000, 15000], 'qty_3': [20, 50, 25, 30], 'url': ['amazon.com', 'ebay.com', 'deals.com', 'ebay.com'] }) # 提取price和qty列的后缀数字 suffixes = [col.split('_')[1] for col in df.columns if col.startswith('price_')] # 生成price_range列:逐行生成字典数组 df['price_range'] = df.apply(lambda row: [ {'price': row[f'price_{s}'], 'qty': row[f'qty_{s}'], 'comments': ''} for s in suffixes ], axis=1) # 保留目标列得到结果 result_df = df[['item_name', 'price_range', 'url']] print(result_df)
代码说明
- 从列名中提取
price_n的后缀数字,确保price和qty的配对对应; - 使用
apply逐行处理数据,为每个后缀数字配对对应的price和qty值,生成包含空comments字段的字典; - 将字典列表赋值给
price_range列,最后筛选出需要的列即可得到目标DataFrame。
内容的提问来源于stack exchange,提问作者Ramineni Ravi Teja
相关产品推荐
相关产品推荐

