我想管理從多方收到的資料并將其轉換為結構化資料,以便在我們的系統中保持統一。
例如,我收到這樣的資料:
- 公稱直徑 1-13 x 0.5 mm
- 公稱直徑 10 mm
- 外徑15mm
- 頭 dm 9.00 毫米
- 直徑 208/20 毫米 高度 218 毫米
目標是按順序檢索此輸出
- M1-13x0.5
- M10
- M15
- M9
- M208/20 H28
我想我會用多個正則運算式來做,然后替換它
df['diameter'] = df['New_size'].str.findall('^nominal diameter\s([\S] )\sx\s([\S] )\smm$')
df['diam2'] = 'Nom.M' df['diameter'].str[0].str[0] 'x' df['diameter'].str[0].str[1]
df['diameter'] = df['New_size'].str.findall('^nominal diameter\s([\S] )\smm$')
df['diam2'] = 'Nom.M' df['diameter'].str[0]
但這僅在搜索直徑時有幫助,在示例 5 中,我需要再次運行它并以某種方式加入以增加高度……
有沒有辦法像 Excel regex 一樣回圈資料并替換正則運算式?還是我的計劃完全愚蠢,有更好的方法來做到這一點?
我想計劃將所有內容分成幾部分并逐字替換。然后只加入我認為必要的那些資訊。但真的似乎我太復雜了Thasnk!
uj5u.com熱心網友回復:
使用這種型別的編輯,你不能第一次就絕對,特別是如果 df 很大并且有不同的文本。上演。
選項 1:替換模式而不是目標子字串
替換df中的值。首先替換除 x 之外的所有 alphas,后跟空格和 digit 之前什么都沒有。然后從字串的開頭替換數字之前的所有非數字。然后替換所有點,后跟 2 個零
df['text_edited'] = df.replace(regex={'[a-wy-z] \s(?=\d)': 'H', '^[\D] (?=\d)': 'M', 'mm': '', '.00':''})
text text_edited
0 nominal diameter 1-13 x 0.5 mm M1-13 x 0.5
1 nominal diameter 10 mm M10
2 for external diameter 15mm M15
3 head dm 9.00 mm M9
4 diameter 208/20 mm height 218 mm M208/20 H218
選項 2:替換目標子字串
我認為您的主要目標是用首字母代替直徑和高度。這樣做,如果有任何不需要的殘差會顯著改變屬性含義,請進一步編輯新列
df['text_edited'] = df.replace(regex={'diameter\s|dm\s': 'M','height\s': 'H','[^MHx0-9\W]':' ', '.00':''})
df['text_edited'] = df['text_edited'].str.strip().str.replace('^[x]','', regex=True)
text text_edited
0 nominal diameter 1-13 x 0.5 mm M1-13 x 0.5
1 nominal diameter 10 mm M10
2 for external diameter 15mm M15
3 head dm 9.00 mm M9
4 diameter 208/20 mm height 218 mm M208/20 H218
uj5u.com熱心網友回復:
我只是使用一系列正則運算式:
df['new_col'] = (
df['col']
.str.replace(r'.*nominal diameter ([\d-] ) x ([\d.] ) mm.*', r'M\1x\2', regex=True)
.str.replace(r'.*nominal diameter ([\d.] ) mm.*', r'M\1', regex=True)
.str.replace(r'.*for external diameter ([\d.] )mm.*', r'M\1', regex=True)
.str.replace(r'.*head dm ([\d.] ) mm.*', r'M\1', regex=True)
.str.replace(r'.*diameter ([\d./] ) mm height ([\d.] ) mm.*', r'M\1 H\2', regex=True)
)
輸出(之前):
>>> df = pd.DataFrame({'d':['nominal diameter 1-13 x 0.5 mm','nominal diameter 10 mm','for external diameter 15mm','head dm 9.00 mm','diameter 208/20 mm height 218 mm',]})
>>> df
col
0 nominal diameter 1-13 x 0.5 mm
1 nominal diameter 10 mm
2 for external diameter 15mm
3 head dm 9.00 mm
4 diameter 208/20 mm height 218 mm
輸出(之后):
>>> df
col new_col
0 nominal diameter 1-13 x 0.5 mm M1-13x0.5
1 nominal diameter 10 mm M10
2 for external diameter 15mm M15
3 head dm 9.00 mm M9.00
4 diameter 208/20 mm height 218 mm M208/20 H218
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444021.html
上一篇:試圖在每組熊貓中標記第一次相遇
下一篇:如何使用引導標簽輸入
