首页 > 解决方案 > 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 列的子字符串。

如何在熊猫中执行此操作?

标签: pythonpandasdataframe

解决方案


尝试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

推荐阅读