当列表值非空时替换DataFrame列中的值
解决方案
构造测试数据
先还原你的示例场景,方便验证效果:
import pandas as pd import numpy as np # 原始DataFrame df = pd.DataFrame({ 'ID': [1, 2, 3, 4, 5, 6], 'Date': ['19/04/2022', '12/07/2022', '27/09/2022', '11/05/2022', '04/10/2022', '02/08/2022'] }) # 待替换的日期列表(空字符串不执行替换) updated_dates = ['20/10/2022', '', '03/10/2022', '14/10/2022', '', '19/10/2022']
方法1:numpy.where(高效简洁)
利用布尔判断列表,批量替换符合条件的行:
# 生成布尔判断:列表元素去除空格后是否非空 mask = [bool(date.strip()) for date in updated_dates] # 非空则用列表值替换,否则保留原Date df['Date'] = np.where(mask, updated_dates, df['Date'])
方法2:pandas.mask(pandas原生方法)
mask方法会在条件为True时替换对应值,刚好匹配需求:
mask = [bool(date.strip()) for date in updated_dates] df['Date'] = df['Date'].mask(mask, updated_dates)
方法3:列表推导式(直观易懂)
逐行遍历原Date和待替换列表,手动判断替换逻辑:
df['Date'] = [new_date if new_date.strip() else old_date for old_date, new_date in zip(df['Date'], updated_dates)]
验证结果
执行任意一种方法后,打印df即可得到你期望的输出:
ID Date 0 1 20/10/2022 1 2 12/07/2022 2 3 03/10/2022 3 4 14/10/2022 4 5 04/10/2022 5 6 19/10/2022
注意:待替换列表的长度必须和DataFrame的行数完全一致,否则会触发长度不匹配的错误。
内容的提问来源于stack exchange,提问作者Gamakichi
相关产品推荐
相关产品推荐

