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

如何检查DataFrame中各类型值是否覆盖全部指定年份并添加标签列

解决Pandas DataFrame按类型添加年份覆盖标签的问题

嗨,我来帮你搞定这个需求!我们可以通过分组统计和字典映射的方式轻松实现给每个type添加对应的标签,具体实现步骤和代码如下:

步骤说明

  • 第一步:分组统计每个type对应的所有年份集合,判断是否包含2017-2020全部四个年份
  • 第二步:生成一个type到标签的映射字典
  • 第三步:将映射字典应用到原DataFrame,生成label列

完整代码示例

import pandas as pd

# 初始化你的DataFrame
df1 = pd.DataFrame({
    'type': ['cst1', 'cst1', 'cst1','cst1','cst2','cst2','cst2','cst3','cst3','cst3','cst3'],
    'year':[2017,2018,2019,2020,2018,2019,2020,2017,2018,2019,2020]
})

# 定义需要检查的目标年份集合
target_years = {2017, 2018, 2019, 2020}

# 分组获取每个type的年份集合,生成标签映射字典
type_label_map = df1.groupby('type')['year'].agg(set).apply(lambda x: 1 if x == target_years else 0).to_dict()

# 添加label列
df1['label'] = df1['type'].map(type_label_map)

# 查看结果
print(df1)

执行结果

执行上述代码后,你会得到符合预期的DataFrame:

typeyearlabel
0cst120171
1cst120181
2cst120191
3cst120201
4cst220180
5cst220190
6cst220200
7cst320171
8cst320181
9cst320191
10cst320201

补充说明

  • 这里利用groupby('type')['year'].agg(set)快速获取每个类型对应的年份集合,避免重复统计
  • 使用lambda函数直接判断集合是否完全匹配目标年份,逻辑清晰简洁
  • 最后通过map方法批量添加标签,效率很高,适合处理较大数据集

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:57:38