python - 在数据框中搜索子字符串并替换它

标签 python string python-3.x pandas dataframe

我遇到了创建虚假数据的情况,我正在尝试清理它。

例如...

www.one@foxturn.com/!ut/5 #RealLink
www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD # System adds junks to it
www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf # System adds junks to it

我正在尝试通过删除 !ut 之后的所有内容来清理此问题

到目前为止我已经尝试过:

SPA_MX = Mexico['Page URL'].str.startswith("http://www.www.one@foxturn.com/ut1")

但这会返回一个 bool 值。

我想了解实现这一目标的最有效方法。

最佳答案

您可以在列上使用 apply 来执行此操作,然后使用 find 返回模式的索引,并在找到时对 str 进行切片:

In[69]:

df['url'].apply(lambda x: x[:x.find('!ut') + 3] if x.find('!ut') != -1 else x)

Out[69]: 
0                             www.one@foxturn.com/!ut
1           www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD
2    www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf
Name: url, dtype: object

关于python - 在数据框中搜索子字符串并替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44907777/

相关文章:

python - 将 Python 字节转换为字符串而不进行编码

python - TypeError : write() argument must be str, 不是字节,升级到 python 3

python - pygame : Repeating an action every x amount of time

r - 在数据框中选择某些字符串

javascript - 限制网页上字符串的显示长度

python - 使用 Python 3 通过蓝牙发送消息

python - 如何在Python中从csv文件中提取行并将其复制到另一个csv文件?

python - Pytest mocker.patch 返回 NonCallableMagicMock

python - 如何在 Python 中正确编写原始多行字符串?

python - Python 函数列表