我有一個資料框,它只有一個名為 ImagePath 的列,這是一個輸入的樣子:
Images/LINE 58/AGSD/LUC/L58_AFND_K3_2022-10-12_23-53-18_Color_ID_511.jpg
這是我要提取的:
2022-10-12_23-53-18
這就是我所擁有的:
dfDate = dfColor['ImagePath'].str.extract(r"^(?:.*?_){3}([^\nColor] )").to_string()
dfDate = pd.to_datetime(dfDate, format='%Y-%m-%d_%H-%M-%S_')
我不想像我現在正在做的那樣創建對那個世界“顏色”的依賴,因為將來可能會有任何其他詞。我想指望“_”并從第 3 和第 5 個下劃線中取出所有內容。
uj5u.com熱心網友回復:
將正則運算式更改為
^(?:[^_]*_){3}([^_]*_[^_]*)
請參閱正則運算式演示。
詳情:
^- 字串的開始(?:[^_]*_){3}- 子串直到(包括)第三個_([^_]*_[^_]*)- 第 1 組(的實際輸出.extract()):零個或多個非下劃線字符,_以及零個或多個非下劃線字符。
解決方案的一種變體:您可能需要組模式來匹配類似日期時間的字串:
^(?:[^_]*_){3}(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})
或者,允許一位數的小時/分鐘/秒/月/日:
^(?:[^_]*_){3}(\d{4}-\d{1,2}-\d{1,2}_\d{1,2}-\d{1,2}-\d{1,2})
請參閱此正則運算式演示。
uj5u.com熱心網友回復:
另一種選擇,與str.split:
dfDate = dfColor['ImagePath'].str.split('_').str[3:5].str.join('_')
dfDate = pd.to_datetime(dfDate, format='%Y-%m-%d_%H-%M-%S')
uj5u.com熱心網友回復:
這是一種方法
# assuming there is a 4 digit following underscore _
# continuing matching until there is underscore and non-digit
_(\d{4}-.*?(?=_\D))
# _ : matches underscore
# (\d{4}- : 4 digits followed by -
# .*? : non-greedy, match all characters
# (?=_\D)) : positive lookahead, an underscore followed by non-digit,
to terminate the match
df['date']=df['url'].str.extract('_(\d{4}-.*?(?=_\D))')
df['date']=pd.to_datetime(df['date'], format='%Y-%m-%d_%H-%M-%S')
df
url date
0 Images/LINE 58/AGSD/LUC/L58_AFND_K3_2022-10-12... 2022-10-12 23:53:18
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515939.html
標籤:熊猫正则表达式提炼
