简体   繁体   English

Pandas 正则表达式匹配部分字符串以替换整个字符串

[英]Pandas regex match part of string to replace whole string

I'm trying to update some strings in pandas columns that have variable endings which need to all be uniform.我正在尝试更新 pandas 列中的一些字符串,这些字符串具有需要统一的可变结尾。

Example string: "Latest 52 Weeks Ending 07-03-22"示例字符串:“最近 52 周结束 07-03-22”

Replacement String: "Latest 52 Wks - W/E 07/03/22"替换字符串:“最近 52 周 - W/E 07/03/22”

The example string text may variate the final date (eg 07-04-22) but I want all "Latest 52 Weeks" to follow the same format as above.示例字符串文本可能会改变最终日期(例如 07-04-22),但我希望所有“最近 52 周”都遵循与上述相同的格式。 I have tried code similar to the following:我尝试过类似于以下的代码:

df['Current Timeframe'] =  [re.sub(r'Latest 52 Weeks.',date52, str(x)) for x in df['Current Timeframe']]

but this ends up with an output like "Latest 52 Wks - W/E 07/03/22Ending 07-03-22" where a portion of the old string is retained at the end.但这最终会出现 output ,例如“最新的 52 周 - W/E 07/03/22Ending 07-03-22”,其中旧字符串的一部分保留在末尾。

You can use the pandas version of string replace into your series.您可以使用 pandas 版本的字符串替换到您的系列中。

df['Current Timeframe'] = df['Current Timeframe'].str.replace("Latest 52 Wks - W/E", "Latest 52 Weeks Ending")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM