如何迭代校验pandas DataFrame并根据A列后缀填充对应B列内容
实现方案
pandas优先推荐使用向量化操作实现需求,执行效率远高于手动遍历,也提供符合要求的遍历实现方式:
方案1:str.endswith条件赋值(最高效)
直接用pandas内置的字符串匹配方法按条件赋值:
# 匹配结尾为gh的行,B列设为Yes heat.loc[heat['A'].str.endswith('gh'), 'B'] = 'Yes' # 匹配结尾为ow的行,B列设为No heat.loc[heat['A'].str.endswith('ow'), 'B'] = 'No' # 匹配结尾为al的行,B列设为Maybe heat.loc[heat['A'].str.endswith('al'), 'B'] = 'Maybe'
该方案不需要遍历全表,适合任意数据量场景,代码逻辑直观好维护。
方案2:后缀映射实现
如果后续规则有扩展,用映射的方式更简洁:
# 定义后缀和B列取值的映射关系 suffix_rule = {'gh':'Yes', 'ow':'No', 'al':'Maybe'} # 提取A列最后两位字符,直接映射得到B列值 heat['B'] = heat['A'].str[-2:].map(suffix_rule)
方案3:遍历实现
如果必须使用遍历逻辑,可选择以下两种方式,仅适合小数据量使用:
3.1 iterrows逐行遍历
for index, row in heat.iterrows(): a_content = row['A'] if a_content.endswith('gh'): heat.loc[index, 'B'] = 'Yes' elif a_content.endswith('ow'): heat.loc[index, 'B'] = 'No' elif a_content.endswith('al'): heat.loc[index, 'B'] = 'Maybe'
3.2 apply行遍历
def get_b_value(row): if row['A'].endswith('gh'): return 'Yes' elif row['A'].endswith('ow'): return 'No' elif row['A'].endswith('al'): return 'Maybe' heat['B'] = heat.apply(get_b_value, axis=1)
内容的提问来源于stack exchange,提问作者apol96
相关产品推荐
相关产品推荐

