尝试使用一列中的值(作为字符串)来确定从另一列中删除的内容。该列的其余部分必须保持不变。
示例数据:
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 | 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
如何删除日期列的内容但保留原始数据?
最佳答案
所以,我尝试了这个并且效果很好:
dfTest['bar'] = dfTest.apply(lambda row : row['foo'].replace(str(row['date']), ''), axis=1)
关于python - 根据另一列从列中删除子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54892624/