【问题标题】:How to replace a character once in a text in a pandas dataframe如何在熊猫数据框中的文本中替换一次字符
【发布时间】:2023-01-17 17:04:19
【问题描述】:

我有一个熊猫数据框“X_test”,其中包含一个索引和一个文本列“review”。我只想检查文本并将字符“b”替换为“6”一次:如果文本多次包含“b”字符,我希望只随机进行一次替换。

例如,下面的代码替换了第 2 行中所有位置的 b:

X_test["modified_review"] = X_test["review"]
X_test.loc[2, "modified_review"]= X_test.loc[2, "modified_review"].replace('b','6')

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要使用自定义函数。

    让我们拆分字符串,并用随机替换的一项将其连接回去:

    import random
    
    def random_sub(s, pat, repl):
        l = s.split(pat)
        new = [pat]*(len(l)-2)+[repl]
        random.shuffle(new)
        return ''.join([e for x in zip(l, new+[None]) for e in x][:-1])
    
    Xtest.loc[2, 'modified_review'] = random_sub(Xtest.loc[2, 'modified_review'], pat='b', repl='6')
    
    print(Xtest)
    

    输出:

      modified_review
    0            aaaa
    1             cbc
    2        aba6abab
    

    【讨论】:

    • if the text contains the 'b' character several times I want the replacement to be done only once randomly.
    • @jezrael 我错过了,然后需要一个自定义函数
    猜你喜欢
    • 2023-01-16
    • 2021-09-07
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多