Python 从 Excel 中的字符串列中提取度量单位和附加编号

Python extract unit of measure and attached number from column of string in Excel

我必须为超过 1000 行中的每个字符串提取度量单位和相关数字,例如:

25 kg, 1000L

字符串如下所示:

ZALTATA MA177-445 IBCC 1000L

数字在计量单位前

假设此示例输入:

                              col
0    ZALTATA MA177-445 IBCC 1000L
1  ZALTATA MA177 445 kg IBCC 1000

你可以使用 extract:

import re
df['col'].str.extract(r'\b(?P<value>\d+)\s*(?P<unit>kg|l)\b', flags=re.I)

输出:

  value unit
0  1000    L
1   445   kg

加入并保存

(df.join(df['col'].str.extract(r'\b(?P<value>\d+)\s*(?P<unit>kg|l)\b', flags=re.I))
   .to_excel('out.xslx')
)