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

标签 python pandas dataframe

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

示例数据:

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/

相关文章:

python - Virtualenv 找不到新安装的 Python 版本

python - 如何从字符串中拆分日期和时间?

python - 如何使用 Pandas.DataFrame 查询方法来获取日期时间或周期类型的索引?

python - Plotly-Dash:如何在不更改图形布局的情况下仅更新图形数据?

python - 计算包含 NaN 的数组之间的距离

python - Scikit LogisticRegression 中的情绪预测错误

pandas - 在 Markdown (Jupyter) 中左对齐整个表格

python - 合并之前清理数据的更好方法是什么?

python - 如何将文本附加到 'column' 值

python - Pandas 按优先级连接/合并两个数据帧