python - 比较数据框中的两个熊猫系列并对其应用说明
问题描述
我一直在尝试比较熊猫数据框中两个系列的子字符串。这两个系列是“标题”和“新闻”,它们分别是我从一个报纸网站上抓取的新闻标题和新闻正文。现在,许多“新闻”索引的第一行都包含标题,我想将其从“新闻”系列中删除。
例如:
df["News"][0] = "Mother Killed, police official injured in Madaripur road accidentA woman was killed .... flee the scene.AH/MUS"
df["titles"][0] = "Mother Killed, police official injured in Madaripur road accident"
我想从新闻中删除标题。在上面的例子中,这应该产生“一个女人被杀......逃离现场.AH/MUS”
我已经这样做了:
df["replaced"] = [(df["News"][i].replace(df["titles"][i], ""))
for i in range(df.shape[0])
]
这确实有效,但我想知道什么应该是最快的方法。具体来说,我正在寻找一种更熊猫的方式,并且不想循环/使用列表理解。有什么方法可以做到这一点,以便我可以将其应用于整个系列而无需循环?
解决方案
尝试它会像魅力一样工作
def getit(row):
try:
return row.get("News").replace(row.get("titles"),"")
except:
return row.get("News") # in case row.get("titles") return non-string
df["replaced"] = df.apply(getit , axis = 1)
推荐阅读
- rabbitmq - 如何找出最后发送消息的是哪个交易所?
- node.js - 无法在 travis 中正确构建/运行测试。没有权限
- python - matplotlib contourf 具有极值
- javascript - 构建字符计数功能
- ios - 在 Xamarin iOS 13 中自定义导航栏不起作用
- r - 根据R中列表中选择的项目显示输入字段
- react-native - 在Press React-Native 上找不到变量
- redis - 无法在redis中获取某些键
- oracle - ORACLE PL/SQL 过程需要 AUTHID CURRENT_USER 才能使用 DDL 立即执行
- kubernetes - 入口控制器和谷歌 kubernetes