python - Pandas - 在某些条件下替换另一列的值
问题描述
我的DataFrame
. 如果第一列中的文本是第二列中的子字符串,我想用第二列替换第一列的值。
例子:
Input:
col1 col2
-----------------
text1 text1 and text2
some text some other text
text 3
text 4 this is text 4
Output:
col1 col2
------------------------------
text1 and text2 text1 and text2
some text some other text
text 3
this is text 4 this is text 4
如您所见,我已经替换了第 1 行和第 4 行,因为第 1 行第 1 列中的文本是第 2 列的子字符串。
如何在熊猫中执行此操作?
解决方案
尝试df.apply
使用axis=1
.
所以这将遍历每一行并检查 col1 是否是 col2 的子字符串。
如果是则返回 col2 否则返回 col1
df['col1'] = df.apply(lambda row: row['col2'] if row['col1'] in row['col2'] else row['col1'], axis=1)
完整代码:
df = pd.DataFrame({'col1': ['text1', 'some text', 'text 3', 'text 4'], 'col2': ['text1 and text2', 'some other text', '', 'this is text 4']})
df['new_col1'] = df.apply(lambda row: row['col2'] if row['col1'] in row['col2'] else row['col1'], axis=1)
df
col1 col2 new_col1
0 text1 text1 and text2 text1 and text2
1 some text some other text some text
2 text 3 text 3
3 text 4 this is text 4 this is text 4
推荐阅读
- c# - 如果 Log4net 由 Windows 服务启动,则不会记录日志
- mysql - 在 mysql 上触发 3 个表
- angular - Angular 中的 observable 是如何工作的?“可观察”类型中缺少属性“包含”
- javascript - 如何反复按保存按钮,但只保存一次数据
- file-permissions - 如何从 Filezilla(或目录搜索)隐藏文件
- python - tf.boolean_mask(2D, 2D) 给出一维结果
- multithreading - 原子操作的副作用是否可以立即被其他线程看到?
- azure - 将 Python 日志记录设置为 Azure Blob,但在那里找不到日志文件
- django - NoReverseMatch in Django:Reverse for ....l' with arguments '('',)' not found. 尝试了 1 种模式:
- android - android studio中的渐变背景