sta*_*tdr 6 python dataframe pandas
尝试使用一列中的值(作为字符串)来确定从另一列中删除的内容。列的其余部分必须保持不变。
示例数据:
import pandas as pd
dfTest = pd.DataFrame({
'date': ['190225', '190225', '190226'],
'foo': ['190225-file1_190225', '190225-file2_190225', '190226-file3_190226']
})
dfTest
Run Code Online (Sandbox Code Playgroud)
结果数据框:
| date | foo
------------------------------------
0 | 190225 | 190225-file1_190225
1 | 190225 | 190225-file2_190225
2 | 190226 | 190226-file3_190226
Run Code Online (Sandbox Code Playgroud)
我需要创建 'bar' 列,其中 'foo' 已删除所有 'date' 匹配项。
我要找的是这个:
| date | foo | bar
-----------------------------------------------
0 | 190225 | 190225-file1_190225 | -file1_
1 | 190225 | 190225-file2_190225 | -file2_
2 | 190226 | 190226-file3_190226 | -file3_
Run Code Online (Sandbox Code Playgroud)
'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']), '')
Run Code Online (Sandbox Code Playgroud)
两者的结果都在下表中(在“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
Run Code Online (Sandbox Code Playgroud)
如何删除日期列的内容但保留原始数据?
小智 7
所以,我试过这个,效果很好:
dfTest['bar'] = dfTest.apply(lambda row : row['foo'].replace(str(row['date']), ''), axis=1)
Run Code Online (Sandbox Code Playgroud)