簡體   English   中英

如何從大型python數據框中的復雜字符串中提取數字

[英]How to extract numbers from a complex string in a large python dataframe

我有一個接近 100 萬行的 python 數據框。 有一個字符串列,其中包含一些數字,例如

 String_Col

 24FT String
 String 24FT
 2 String 20FT
 20 String 3

我需要從此列中提取24,24,20,20並將其另存為新列。 我可以迭代每個單元格並進行字符串轉換,但這會消耗大量時間來處理大型數據集。

任何想法表示贊賞。

您可以使用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)

如果你想在FT之前正好有 2 位數字,請使用re.findall(r"\\d{2}(?=FT)",x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM