python - 熊猫更换条件问题
问题描述
如果值在字符串中包含单词(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 伤病数据
框架看起来像这样: 在此处输入图像描述
解决方案
我将构建一个自定义函数,然后应用于字符串列:
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)
推荐阅读
- javascript - JavaScript 警报消息不起作用
- python - python - 捕获用户的鼠标输入
- javascript - Grunt cssmin 和时间戳文件名
- c# - 将两个 C# DbGeography 多边形连接成一个多多边形
- sql - 清理我试图在 SQL 中创建的时间线
- sql - 左连接不起作用 - 它忽略了左表的记录
- powerbuilder - UFT 上的 PbDataWindow 右键单击问题
- javascript - JS:检查单个字符是否不是空格
- apache-kafka - ElasticsearchSinkConnector 无法将数据反序列化到 Avro
- android - 多个dex文件定义Lcom/google/android/gms/internal/measurement/zzabn