简体   繁体   English

如何在 Excel 中的 Python 或 VBA 中替换千位分隔符并保留其他逗号

[英]How to replace the thousand separator and keep other commas in Python or VBA in Excel

I have a column named 'policy' with rows of data like this:我有一个名为“policy”的列,其中包含如下数据行:

media A,type A,2019-08-29 to 2019-12-31,0.00 CNY ≤ amount ≤ 10,000,000.00 CNY, 10.50%, --;media B,type B,2019-08-29 to 2019-12-31,0.00 CNY ≤ amount ≤ 10,000,000.00 CNY, 10.50%, --; media A,type A,2019-08-29 to 2019-12-31,0.00 CNY ≤ 金额 ≤ 10,000,000.00 CNY, 10.50%, --;media B,type B,2019-08-29 to 2019-12-31, 0.00 CNY ≤ 金额 ≤ 10,000,000.00 CNY, 10.50%, --;

It's a combination of field values separated by commas.它是由逗号分隔的字段值的组合。

Now I want to replace all the thousand separators within the numbers like '0.00 CNY ≤ amount ≤ 10,000,000.00 CNY'.现在我想替换数字中的所有千位分隔符,如“0.00 CNY ≤ 金额 ≤ 10,000,000.00 CNY”。 I tried to use regex to replace them:我尝试使用正则表达式来替换它们:

df['policy'].replace(to_replace=r'(?<=\d{1,3})\,(?=\d{3})', value='', regex=True)

but Python raises an error says 'look-behind requires fixed-width pattern'.但是 Python 引发了一个错误,说“后视需要固定宽度的模式”。

I hope I can get results like:我希望我能得到如下结果:

media A,type A,2019-08-29 to 2019-12-31,0.00 CNY ≤ amount ≤ 10000000.00 CNY, 10.50%, --;media B,type B,2019-08-29 to 2019-12-31,0.00 CNY ≤ amount ≤ 10000000.00 CNY, 10.50%, --; media A,type A,2019-08-29 to 2019-12-31,0.00 CNY ≤ 金额 ≤ 10000000.00 CNY, 10.50%, --;media B,type B,2019-08-29 to 2019-12-31, 0.00 CNY ≤ 金额 ≤ 10000000.00 CNY, 10.50%, --;

Since the digit of the number is uncertain, ie, it could be 1,000.00, 10,000,000.00, or 999,999.00, I can't write fixed-width pattern.由于数字的位数不确定,即可能是 1,000.00、10,000,000.00 或 999,999.00,我无法写出固定宽度的模式。 I wonder whether there is a way to replace them in Python or probably some kind of VBA script I can run in Excel.我想知道是否有办法在 Python 中替换它们,或者可能是我可以在 Excel 中运行的某种 VBA 脚本。

Any ideas would be fine, thanks.任何想法都可以,谢谢。

The number of digit before the first comma you want to replace doesn't matter.您要替换的第一个逗号之前的位数无关紧要。

A regex like (?<=\\d{1})\\,(?=\\d{3}) should be able to find all the commas you want to replace.(?<=\\d{1})\\,(?=\\d{3})这样的正则表达式应该能够找到所有要替换的逗号。

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

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