基于国家标识在Python中为完全缺少年份的国家填充年份序列
解决方案
步骤说明
要实现仅为年份完全缺失且记录数匹配目标年份序列长度的国家填充完整年份序列,可按以下步骤操作:
- 统一缺失值格式:将
year列的空字符串转换为NaN,方便后续缺失值判断。 - 生成目标年份序列:创建2023到2003的降序年份列表。
- 筛选需填充的国家:分组统计每个国家的年份缺失情况和记录数,筛选出「所有年份缺失」且「记录数与目标年份序列长度一致」的国家。
- 填充年份字段:对筛选出的国家,按行索引对应到目标年份序列,替换
year字段。
完整代码
import pandas as pd import numpy as np # 加载原始数据 data = {'country': ['USA', 'USA', 'USA', 'China', 'China', 'China', 'India', 'India', 'India', 'France', 'Pakistan', 'Pakistan', 'Pakistan', 'Bangladesh'], 'year': [2023, 2022, 2021, '', '', '', 2023, 2022, 2021, '', '', '', '', ''], 'value1': [10, 15, 20, 30, 35, 40, 50, 60, 9, 10, 11, 12, 13, 11], 'value2': [55, 15, 21, 22, 33, 45, 50, 60, 9, 10, 11, 12, 13, 9]} df = pd.DataFrame(data) # 1. 将空字符串转为NaN,统一缺失值格式 df['year'] = df['year'].replace('', np.nan) # 2. 定义要填充的年份序列(2023至2003降序) # 若为样本简化场景(仅填充2023-2021),可替换为:target_years = [2023, 2022, 2021] target_years = list(range(2023, 2002, -1)) target_length = len(target_years) # 3. 分组统计,筛选需填充的国家 country_stats = df.groupby('country').agg( all_year_missing=('year', lambda x: x.isna().all()), record_count=('year', 'size') ).reset_index() # 筛选条件:所有年份缺失 + 记录数匹配目标年份序列长度(对应示例中的中国、巴基斯坦) fill_countries = country_stats[ (country_stats['all_year_missing']) & (country_stats['record_count'] == target_length) ]['country'].tolist() # 4. 为目标国家填充年份 df['year'] = df.apply( lambda row: target_years[df[df['country'] == row['country']].index.get_loc(row.name)] if row['country'] in fill_countries else row['year'], axis=1 ) # 查看结果 print(df)
代码解释
- 缺失值统一:
replace('', np.nan)让pandas能准确识别年份缺失状态,避免空字符串干扰判断。 - 年份序列生成:
range(2023, 2002, -1)通过负步长生成从2023递减到2003的完整年份列表,符合需求的降序要求。 - 国家筛选逻辑:通过
groupby聚合统计,精准定位需要填充的国家,排除仅1-3条记录且年份缺失的国家(如示例中的法国、孟加拉国)。 - 精准填充:利用
apply函数结合组内索引,为目标国家的每一行匹配对应年份,保证序列的连续性和正确性。
内容的提问来源于stack exchange,提问作者Researcher
相关产品推荐
相关产品推荐

