簡體   English   中英

Pandas 如何通過正則表達式從列中提取到多行?

[英]Pandas how can I extract by regex from column into multiple rows?

我有以下數據:

ID 內容 日期
1 2429(薩赫:MySpezialItem:16.59) 2022-04-12
2 2429(薩赫:項目 13:18.59)(薩赫:這個和那個成本:16.59) 2022-06-12

我想實現以下目標:

ID 數字 價格 日期
1 2429 2022-04-12
1 16.59 2022-04-12
2 2429 2022-06-12
2 18.59 2022-06-12
2 16.59 2022-06-12

我試過的

df['sach'] = df['content'].str.split(r'\(sach:.*\)').explode('content')
df['content'] = df['content'].str.replace(r'\(sach:.*\)','', regex=True)

您可以將單個正則表達式與str.extractall一起使用:

regex = r'(?P<number>\d+)\(|:(?P<price>\d+(?:\.\d+)?)\)'

df = df.join(df.pop('content').str.extractall(regex).droplevel(1))

注意。 如果你想要一個新的 DataFrame,不要pop

df2 = (df.drop(columns='content')
         .join(df['content'].str.extractall(regex).droplevel(1))
       )

output:

   ID        date number  price
0   1  2022-04-12   2429    NaN
0   1  2022-04-12    NaN  16.59
1   2  2022-06-12   2429    NaN
1   2  2022-06-12    NaN  18.59
1   2  2022-06-12    NaN  16.59

正則表達式演示

暫無
暫無

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

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