You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于模式分组列的PySpark实现:将价格数量列转为字典数组

DataFrame列重组为字典数组

问题描述

需要将输入DataFrame中的price_n和qty_n列按数字后缀分组,转换为包含price、qty、comments字段的字典数组,最终生成新的price_range列。

输入DataFrame

item_nameprice_1qty_1price_2qty_2price_3qty_3url
Samsung Z100005900010700020amazon.com
Moto G412000101000020600050ebay.com
Mi 4i15000812000201000025deals.com
Moto G320000518000121500030ebay.com

期望输出DataFrame

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

代码说明

  1. 从列名中提取price_n的后缀数字,确保price和qty的配对对应;
  2. 使用apply逐行处理数据,为每个后缀数字配对对应的price和qty值,生成包含空comments字段的字典;
  3. 将字典列表赋值给price_range列,最后筛选出需要的列即可得到目标DataFrame。

内容的提问来源于stack exchange,提问作者Ramineni Ravi Teja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:50:22