python - Pandas - 有条件地连接两列
问题描述
给定一个数据框
Patient ID Instructions ID Replaced
1 N/A ID123
2 ID124
3 ID125
4 xyz ID126
5 xyz ID127
6 ID128
7 Replacement ID129
8 Replace ID130
9 replaced ID131
10 xyz ID132
如果找到子字符串Instructions
,如何创建一个新列?ID Replaced
replac
Patient ID Instructions ID Replaced Comments
1 N/A ID123
2 ID124
3 ID125
4 xyz ID126
5 xyz ID127
6 ID128
7 Replacement ID129 Replacement | ID129
8 Replace ID130 Replace | ID130
9 Replaced ID131 Replaced | ID131
10 xyz ID132
我尝试了以下但该Comments
列完全为空
mani_df['Comments'] = ""
# if instructions contains 'replac' , concat with ID replaced
if "replace" in df['Instructions']:
df['Comments'] = df['Instructions'].str.cat(df['ID Replaced'], sep = " | ")
我尝试使用布尔掩码,但这会为前两行返回 False
mask = mani_df['Special Handling Directions'].str.contains('replac')
Out[55]:
0 False
1 False
2 NaN
3 NaN
解决方案
您可以使用str.contains
withcase=False
和 concat usingpandas indexing
mask = df.Instructions.str.contains('Replace', case=False).fillna(False)
df['Comments'] = df.loc[mask, 'Instructions'] + ' | ' + df['ID Replaced']
当然,fillna
最后你可以得到空字符串(看起来像你预期的输出)
df.fillna('')
产量
Patient ID Instructions ID Replaced Comments
0 1 ID123
1 2 ID124
2 3 ID125
3 4 xyz ID126
4 5 xyz ID127
5 6 ID128
6 7 Replacement ID129 Replacement | ID129
7 8 Replace ID130 Replace | ID130
8 9 replaced ID131 replaced | ID131
9 10 xyz ID132
推荐阅读
- java - 无法导入 org.apache.commons.lang3.builder 以使用 EqualsBuilder
- swift - 使用自动布局将 3 个图像视图实际放置在相同的高度
- c++ - 检查一个对象的类是否派生自C++中另一个对象的类
- typescript - 部署云功能时如何传递证书密钥文件?
- javascript - 动态遍历未知深度的对象的键
- vue.js - Vue Router Auth Guard url 额外字符
- eclipse-hono - Hono 部署后的端口映射
- python - 沿轴计算多维数组中某个值的百分位排名
- php - 表单数据未在 MySql 数据库中提交
- spring - Spring 集成 ByteArrayRawSerializer TCP Client Server