【问题标题】:How to replace specific last string in a dataframe column如何替换数据框列中的特定最后一个字符串
【发布时间】:2022-01-16 15:02:55
【问题描述】:

如果数据框列中的最后一个单词是特定文本,我会尝试替换它。下面是我的代码

import pandas as pd

lst = ['Main Close', 'Jon cl', 'Boon lose', 'Saint Cls', 'Brook CL','Smith clo', 'Petes Cl', 'Klein Cl.', 'Chuks Close']
df = pd.DataFrame(lst, columns = ['address'])

replace_values = {'Cl$' : 'Close', 'lose$' : 'Close', 'close$' : 'Close', 'cl$' : 'Close', 'Cl.$' : 'Close', 'CL$' : 'Close', 'clo$' : 'Close', 'CI$' : 'Close'}

for key, value in replace_values.items():
    df.address = df['address'].str.replace(key, value)

我使用字典来存储搜索值和替换值。我遇到了问题,因为它与特定文本不匹配,即

Main Close 被修改为 Main CClose 但它应该被忽略

Pete Cl 被修改为 Petes CClose 但应该是 Petes Close

我可能会错过什么。我尝试使用其他问题中的许多其他解决方案,但无法弄清楚。

【问题讨论】:

  • "lose" 匹配 "Close" 作为正则表达式。我猜你需要r"\blose\b" 来强制与这些单词边界进行“精确”匹配。
  • 我试过你的建议没有任何效果。
  • 对我有用,很有趣。 {'Cl$': 'Close', '\\blose\\b': 'Close', 'close$': 'Close', 'cl$': 'Close', 'Cl.$': 'Close', 'CL$': 'Close', 'clo$': 'Close', 'CI$': 'Close'} 是我使用的字典,唯一的变化是上面提到的那个。
  • 是的 \b 断言单词边界,你知道 $ 我想已经知道了。 regex101.com 是个好网站。

标签: python pandas dataframe replace


【解决方案1】:

试试regexdf.apply

>>> import re
def f1(s):
    p = re.compile('^(\S+)\s+(cl|cl.|Cl|Cl.|CL|Cls|clo|lose|Close)$')
    return p.sub('\\1 Close', s)

>>> df['address'] = df['address'].apply(f1)

>>> print(df)

    address
0   Main Close
1    Jon Close
2   Boon Close
3  Saint Close
4  Brook Close
5  Smith Close
6  Petes Close
7  Klein Close
8  Chuks Close

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多