繁体   English   中英

根据另一列从列中删除子字符串

[英]Remove substring from column based on another column

尝试使用一列中的值(作为字符串)来确定从另一列中删除的内容。 列的剩余部分必须保持不变。

示例数据:

import pandas as pd

dfTest = pd.DataFrame({
    'date': ['190225', '190225', '190226'],
    'foo': ['190225-file1_190225', '190225-file2_190225', '190226-file3_190226']
})

dfTest

结果数据框:

   |    date   |          foo
------------------------------------
0  |   190225  | 190225-file1_190225
1  |   190225  | 190225-file2_190225
2  |   190226  | 190226-file3_190226

我需要创建'bar'列,其中'foo'删除了所有'date'匹配项。

我要找的是这个:

   |    date   |         foo          |   bar
-----------------------------------------------
0  |   190225  | 190225-file1_190225  | -file1_
1  |   190225  | 190225-file2_190225  | -file2_
2  |   190226  | 190226-file3_190226  | -file3_

'date'列的内容,无论它们出现在开头,中间还是结尾,都需要为'foo'的每一行删除。

我尝试了一些像下面的代码,但它不起作用。 它只是复制原始列而不替换任何东西。 请注意,更改regex = False不会影响结果。

dfTest['bar'] = dfTest['foo'].str.replace(str(dfTest['date']), '')

#or (removing .str, gives same result):

#dfTest['bar'] = dfTest['foo'].replace(str(dfTest['date']), '')

两者都导致下表('bar'中完全相同):

   |    date   |         foo          |         bar
-----------------------------------------------------------
0  |   190225  | 190225-file1_190225  | 190225-file1_190225  
1  |   190225  | 190225-file2_190225  | 190225-file2_190225  
2  |   190226  | 190226-file3_190226  | 190226-file3_190226  

如何删除日期列的内容,否则保留原始数据?

Eddited:我注意到在lambda上替换它没有按预期工作,所以我分成一个函数。

def replace(str1, str2):
    return str1.replace(str2, '')


dfTest['bar'] = dfTest.apply(lambda row: replace(row['foo'], row['date']), axis=1)

所以,我试过这个并且效果很好:

dfTest['bar'] = dfTest.apply(lambda row : row['foo'].replace(str(row['date']), ''), axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM