有条件的熊猫替换

时间:2020-04-13 21:46:34

标签: python pandas

如果值在字符串中具有(dtd),(dnp),(不确定地),(针对整个季节)中的单词,我想将严重性列下的值替换为(1-4)级

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

"time":"1600-12-31 18:46:16"

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

框架如下所示: enter image description here

1 个答案:

答案 0 :(得分:0)

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

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)
相关问题