首页 > 解决方案 > 比较数据框中的两个熊猫系列并对其应用说明

问题描述

我一直在尝试比较熊猫数据框中两个系列的子字符串。这两个系列是“标题”和“新闻”,它们分别是我从一个报纸网站上抓取的新闻标题和新闻正文。现在,许多“新闻”索引的第一行都包含标题,我想将其从“新闻”系列中删除。

例如:

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])
                 ]

这确实有效,但我想知道什么应该是最快的方法。具体来说,我正在寻找一种更熊猫的方式,并且不想循环/使用列表理解。有什么方法可以做到这一点,以便我可以将其应用于整个系列而无需循环?

标签: pythonpandas

解决方案


尝试它会像魅力一样工作

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)

推荐阅读