首页 > 解决方案 > 熊猫更换条件问题

问题描述

如果值在字符串中包含单词(dtd),(dnp),(out indefintely),(out for season),我想将列严重性下的值替换为级别(1-4)

我尝试使用字典替换,但它不会更改列下的元素

df['Severity'] = ""
df['Severity'] = df['Notes']
replace_dict = {'DTD':1,'DNP':2,'out indefinitely':3,'out for season':4}
df['Severity'] = df['Severity'].replace(replace_dict)

我正在清理 2018-19 赛季的 NBA 伤病数据

框架看起来像这样: 在此处输入图像描述

标签: pythonpandas

解决方案


我将构建一个自定义函数,然后应用于字符串列:

def replace_severity(s):
    """matches string `s` for keys in `replace_dict` returning values from `replace_dict`"""

    # define the keys + matches
    replace_dict = {'DTD':1,'DNP':2,'out indefinitely':3,'out for season':4}

    for key, value in replace_dict.items():
        if re.search(key, s, re.I):
            return value

    # if no results
    return None

# Apply this function to your column
df['Severity'] = df['Notes'].apply(replace_severity)

推荐阅读