【问题标题】:Pandas: Truncate string in column based on substring pulled from other column (Python 3)Pandas:根据从其他列中提取的子字符串截断列中的字符串(Python 3)
【发布时间】:2020-10-21 00:52:52
【问题描述】:

我有一个包含两个相关列的数据框,“rm_word”和“article”。

数据样本:

,grouping,fts,article,rm_word
0,"1",fts,"This is the article. This is a sentence. This is a sentence. This is a sentence. This goes on for awhile and that's super ***crazy***. It goes on and on.",crazy

我想查询每篇“文章”的最后 100 个字符,以确定其所在行的相应“rm_word”是否出现。如果是这样,那么我想从“文章”中删除出现“rm_word”的整个句子以及它后面的所有句子。

期望的结果(当“crazy”是“rm_word”时):

,grouping,fts,article,rm_word
0,"1",fts,"This is the article. This is a sentence. This is a sentence. This is a sentence.",crazy

此掩码能够确定文章何时包含其“rm_word”,但我在句子删除位方面遇到了问题。

mask = ([ (str(a) in b[-100:].lower()) for a,b in zip(df["rm_word"], df["article"])])

print (df.loc[mask])

任何帮助将不胜感激!非常感谢。

【问题讨论】:

  • 您还想删除rm_word 周围的"***" 吗?
  • @kait 我手动添加了星号只是为了强调 rm_word。整个句子(以及它后面的所有内容)都应该删除。

标签: python arrays python-3.x pandas list


【解决方案1】:

这行得通吗?

df = pd.DataFrame(
    columns=['article', 'rm_word'],
    data=[["This is the article. This is a sentence. This is a sentence. This is a sentence.", 'crazy'],
          ["This is the article. This is a sentence. This is a sentence. This is a sentence. This goes on for awhile and that's super crazy. It goes on and on.", 'crazy']]
)

def clean_article(x):
    if x['rm_word'] not in x['article'][-100:].lower():
        return x
    article = x['article'].rsplit(x['rm_word'])[0]
    article = article.split('.')[:-1]
    x['article'] = '.'.join(article) + '.'
    return x


df = df.apply(lambda x: clean_article(x), axis=1)
df['article'].values

返回

array(['This is the article. This is a sentence. This is a sentence. This is a sentence.',
       'This is the article. This is a sentence. This is a sentence. This is a sentence.'],
      dtype=object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多