Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个接近 1M 行的 python 数据框。有一个字符串列,其中包含一些数字,例如
String_Col 24FT String String 24FT 2 String 20FT 20 String 3
我需要24,24,20,20从该列中提取并将其另存为新列。我可以遍历每个单元格并进行字符串转换,但这对于大型数据集会消耗大量时间。
24,24,20,20
任何想法表示赞赏。
您可以使用regex匹配模式
regex
import re def func(x): result = re.findall(r"\d+(?=FT)",x) if not result: try: return int(x[:2]) except: return None return result[0] df["num_col"] = df["String_Col"].apply(func)
如果您之前想要 2 位数字FT,请使用re.findall(r"\d{2}(?=FT)",x)
FT
re.findall(r"\d{2}(?=FT)",x)