輸入
Column
0 2 mm
1 3 kg
2 4 m
3名
4 2 mm
5 3 mph
6 full
7 left
在這里,我需要從表中洗掉單位。 我試著用
df["Column"] = df["Column"] 。 replace("D", "", regex = True)
它給我錯誤的輸出。
預期輸出:
Column
0 2
1 3
2 4
3 名稱
4 2
5 3
6 全程
7 left
uj5u.com熱心網友回復:
你可以使用
df["Column"] = df["Column"] 。 str.replace(r'(d)s*[a-zA-Z] $', r'1', regex=True)
請看regex演示。Regex詳情:
(d)- 第1組(1編號的反向參考指的是替換模式中的這個組值):任何數字s*- 零或更多的空白 。
[a-zA-Z]- 一個或多個ASCII字母 。
$--字串的結束。
uj5u.com熱心網友回復:
你仍然可以使用你的replace
s = df.Column.replace('[^0-9] ','', regex=True)
df.Column = df.Column.mask(s! ='',s)
Out[27]。
02
13
2 4
3 名稱
4 2
5 3
6 全程
7 left
名稱。Column, dtype: 物件
uj5u.com熱心網友回復:
你可以使用str.extract:如果該行以數字^d 開始,就得到它或者|保留整個行.*.
df['Column'] = df['Column'] 。 str.extract(r'(^d |.*) ')
print(df)
#輸出
欄目
0 2
1 3
2 4
3 名稱
4 2
5 3
6 全程
7 left
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307542.html
標籤:
下一篇:只在括號內替換逗號的Regex
