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

Pandas分组字符串值:按Booking统计订单及获取唯一城市列表

解决方案

原数据集

import pandas as pd

df = pd.DataFrame({
    "booking": ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C'],
    "city": ['a', 'b', 'c', 'c', 'a', 'a', 'b', 'b', 'c', 'd', 'e'],
    "orders": [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
})

获取每个booking对应的唯一城市列表

要生成你需要的needed_df,可以通过分组提取唯一城市后转为列表:

# 分组提取唯一城市并转为列表
city_series = df.groupby('booking')['city'].unique().apply(list)
# 转为目标DataFrame
needed_df = city_series.reset_index(name='city_list')

运行后needed_df的输出与你期望的完全一致:

booking    city_list
0       A  [a, b, c]
1       B     [a, b]
2       C  [c, d, e]

合并订单总和列表生成完整结果

结合你已实现的订单总和计算代码,将两部分合并为包含完整信息的DataFrame:

# 计算每个booking对应的订单总和列表(你提供的代码)
order_sum_series = df.groupby(['booking', 'city'])['orders'].sum().groupby(level=0).apply(list)

# 合并两个Series生成最终DataFrame
final_df = pd.DataFrame({
    'booking': city_series.index,
    'city_list': city_series.values,
    'order_sum_list': order_sum_series.values
})

final_df的输出结果:

booking    city_list order_sum_list
0       A  [a, b, c]    [10, 10, 20]
1       B     [a, b]       [20, 20]
2       C  [c, d, e]    [10, 10, 10]

内容的提问来源于stack exchange,提问作者bluekit46

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:03:22