我想從每一行中提取一些資料,并制作現有或新資料框的新列,而無需重復執行相同的 re 操作。匹配。
這是資料框的一個條目的外觀:
00:00 Someones_name: some text goes here
我有一個正則運算式,它成功地接受了我需要的 3 個組:
re.match(r"^(\d{2}:\d{2}) (.*): (.*)$", x)
我遇到的問題是,如何在不實際匹配每個新列的情況下采用matched_pa??rt[1]、[2] 和[3]。
我不想要的解決方案是:
new_df['time'] = old_df['text'].apply(function1)`
new_df['name'] = old_df['text'].apply(function2)`
new_df['text'] = old_df['text'].apply(function3)`
def function1(x):
return re.match(r"^(\d{2}:\d{2}) (.*): (.*)$", x)[1]
uj5u.com熱心網友回復:
您可以將str.extract與您的模式一起使用
df[['time','name', 'text']] = df['col1'].str.extract(r"^(\d{2}:\d{2}) (.*): (.*)$")
print(df)
# col1 time name \
# 0 00:00 Someones_name: some text goes here 00:00 Someones_name
# text
# 0 some text goes here
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478541.html
