如何使用另一列删除字符串中未使用的部分

2024-09-30 23:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如何删除另一列中字符串used值的未使用部分?你知道吗

我有:

Col1         Col2
bbbb2         Hello I want to removebbbb2

Output:
Hello I want to bbbb2

我想用结构提取物或者其他解决方案?你知道吗

编辑: @埃罗考尔 但我想删除所有行,例如

Col1        Col2                                           output
bbbb2     Hello I want to removebbbb2        Hello I want to bbbb2
aaaa1     Hello I want to remaaaa1           Hello I want to aaaa1

你的解决方案只有一个例子


Tags: to字符串编辑hellooutput解决方案结构used
2条回答

lambda一起使用.apply

演示:

import pandas as pd

df = pd.DataFrame({"Col1":["bbbb2", "aaaa1"], "Col2":["Hello I want to removebbbb2", "Hello I want to remaaaa1"]})
def rep(row):
    s = row["Col2"].split()
    s[-1] = row["Col1"]
    return " ".join(s)

print(df.apply(lambda row: rep(row), axis=1))

输出:

0    Hello I want to bbbb2
1    Hello I want to aaaa1
dtype: object

例如,您可以将除bbbb2之外的所有字符进行细分。你知道吗

df = pd.DataFrame(data={"Col1": ["bbbb2"], "Col2": ["Hello I want to removebbbb2"]})

df["Col2"].str.replace("(?:\S*)?(bbbb2)(?:\S*)?", "\\1")

Out[29]: 
0    Hello I want to bbbb2
Name: Col2, dtype: object

编辑:对于多行,例如

import re
df = pd.DataFrame(data={"Col1": ["bbbb2", "aaaa1"], "Col2": ["Hello I want to removebbbb2", "Hello I want to remaaaa1"]})
df["out"] = df.apply(lambda x: re.sub("(?:\S*)?(" + x[0] + ")(?:\S*)?", "\\1", x[1]), axis=1)

df
Out[127]: 
    Col1                         Col2                    out
0  bbbb2  Hello I want to removebbbb2  Hello I want to bbbb2
1  aaaa1     Hello I want to remaaaa1  Hello I want to aaaa1

相关问题 更多 >