如何用Pandas计算数据集中各门店的开业时长(年)
用Pandas计算门店开业时长并新增列
先把你的示例数据整理为标准表格:
| year | store name |
|---|---|
| 2000 | Store A |
| 2001 | Store A |
| 2002 | Store A |
| 2003 | Store A |
| 2000 | Store B |
| 2001 | Store B |
| 2002 | Store B |
| 2000 | Store C |
完全可以用Pandas实现需求,核心是通过分组(groupby)结合transform方法,把每个门店的开业时长(最大年份-最小年份)广播到原数据的每一行,直接新增一列。
具体操作步骤:
- 导入Pandas并加载数据集(以下用示例数据演示)
import pandas as pd # 构造示例数据(实际使用时替换为你的数据集加载代码) data = { 'year': [2000,2001,2002,2003,2000,2001,2002,2000], 'store name': ['Store A','Store A','Store A','Store A','Store B','Store B','Store B','Store C'] } df = pd.DataFrame(data)
- 新增
opening_duration列,计算每个门店的开业时长
# 按门店名称分组,计算每组的年份差,并用transform把结果广播到该门店的所有行 df['opening_duration'] = df.groupby('store name')['year'].transform(lambda x: x.max() - x.min())
执行后得到的结果:
| year | store name | opening_duration |
|---|---|---|
| 2000 | Store A | 3 |
| 2001 | Store A | 3 |
| 2002 | Store A | 3 |
| 2003 | Store A | 3 |
| 2000 | Store B | 2 |
| 2001 | Store B | 2 |
| 2002 | Store B | 2 |
| 2000 | Store C | 0 |
补充:只需要门店汇总结果的情况
如果不需要给原数据新增列,仅需每个门店的开业时长汇总表,可直接用agg方法:
summary_df = df.groupby('store name')['year'].agg(opening_duration=lambda x: x.max()-x.min()).reset_index()
汇总结果:
| store name | opening_duration |
|---|---|
| Store A | 3 |
| Store B | 2 |
| Store C | 0 |
内容的提问来源于stack exchange,提问作者rc305
相关产品推荐
相关产品推荐

