Pandas如何根据match_id范围条件为season列指定行填充数值
实现代码
你可以直接用pandas的条件索引完成批量赋值,一行代码即可实现需求:
df_raw.loc[df_raw['match_id'].between(1, 59, inclusive='both'), 'season'] = 2017
代码说明
df_raw['match_id'].between(1, 59, inclusive='both')用于筛选所有match_id在1到59闭区间内的行,你也可以换成更直观的写法,效果完全一致:df_raw.loc[(df_raw['match_id'] >= 1) & (df_raw['match_id'] <= 59), 'season'] = 2017- 如果后续需要填充其他赛季的数值,只要修改对应
match_id的筛选范围和赋值的赛季数值即可,比如要给match_id 60-119的行填充2018,再加一行对应赋值语句即可。
结果验证
填充完成后可以运行以下代码校验结果是否符合预期:
# 查看match_id边界值的season填充情况 print(df_raw[df_raw['match_id'].isin([1, 59, 60])][['match_id', 'season']].drop_duplicates())
正常输出结果如下:
match_id season 0 1 2017.0 xxx 59 2017.0 yyy 60 NaN
内容的提问来源于stack exchange,提问作者Faheeem Sajjad
相关产品推荐
相关产品推荐

