【问题标题】:alter specific characters in pandas更改 pandas 中的特定字符
【发布时间】:2019-12-27 05:34:57
【问题描述】:

背景

我有以下df,其中包含标记化的TextP_Name 列,是including word boundary in string modification to be more specific 的修改

P_Name = [list(['Steven', 'I','Jobs']),
          list(['A', 'Ma', 'Mary']),
          list(['U','Kar', 'Jacob'])]

Text =  [list(['Steven', 'I','Jobs', 'likes', 'apples','I', 'too']),
        list(['A','i', 'like', 'A', 'lot', 'of','sports','cares', 'A', 'Ma', 'Mary']),
        list(['the','U', 'Kar', 'Jacob', 'what', 'about', 'U', 'huh','?'])]

import pandas as pd
df = pd.DataFrame({'Text' : Text,  
                  'P_ID': [1,2,3], 
                  'P_Name' : P_Name,

                 })
df
   P_ID    P_Name            Text
0   1   [Steven, I, Jobs]   [Steven, I, Jobs, likes, apples, I, too]
1   2   [A, Ma, Mary]       [A, i, like, A, lot, of, sports, cares, A, Ma, Mary]
2   3   [U, Kar, Jacob]     [the, U, Kar, Jacob, what, about, U, huh, ?]

目标

1) 使用P_Name 中的名称通过放置**block** 来阻止Text 列中的相应文本

2) 产生一个新列New_Text

试过

来自including word boundary in string modification to be more specific

我已经修改了代码并尝试了以下

df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]

这与我想要的很接近,但不完全是因为有些字母被不恰当地标记为**block** 例如I 在行中0

 P_ID P_Name Text New_Text
    0             [**block**, **block**, **block**, likes, apples, **block**, too]
    1             [**block**, i, like, **block**, lot, of, sports, cares, **block**, **block**, **block**]
    2             [the, **block**, **block**, **block**, what, about, **block**, huh, ?]

期望的输出

P_ID P_Name Text New_Text
    0              [**block**, **block**, **block**, likes, apples, I, too]
    1              [A, i, like, A, lot, of, sports, cares, **block**, **block**, **block**]
    2              [the, **block**, **block**, **block**, what, about, U, huh, ?]

问题

如何进一步修改

df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]

或者使用新代码来实现我想要的输出?

【问题讨论】:

    标签: python string pandas text replace


    【解决方案1】:

    您希望P_Name 序列在Text 标记中的每个有序出现。这可以通过迭代 Text 令牌并检查整个 P_Name 令牌的相等性来实现:

    df["New_Text"] = df["Text"].apply(lambda tokens: tokens.copy())  # copy original tokens
    for tokens, name in zip(df["New_Text"], df["P_Name"]):
        for i, token in enumerate(tokens):
            if tokens[i:i + len(name)] == name:
                tokens[i:i + len(name)] = ["**block**"] * len(tokens[i:i + len(name)])
    

    根据您的用例,您可能会使用未标记的 Text (& P_name)。如果是这样,则可以改为进行子字符串匹配,然后执行标记化。

    【讨论】:

    • 感谢您的帮助。我尝试运行上面的代码,但出现错误NameError: name 'masked_tokens' is not defined
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多