ใช้เมธอด str.replace() ร่วมกับ Regular Expression \d+ เพื่อลบตัวเลขทั้งหมดออกจากสตริงในคอลัมน์ที่ต้องการ
ตัวอย่างโค้ด
import pandas as pd
# Create DataFrame with student records
dataFrame = pd.DataFrame({
"Id": ['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07'],
"Name": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'],
"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass']
})
print("DataFrame ...\n", dataFrame)
# Remove numbers from 'Id' column
dataFrame['Id'] = dataFrame['Id'].str.replace('\d+', '')
print("\nUpdated DataFrame...\n", dataFrame)
ผลลัพธ์
DataFrame ...
Id Name Result
0 S01 Jack Pass
1 S02 Robin Fail
2 S03 Ted Pass
3 S04 Robin Fail
4 S05 Scarlett Pass
5 S06 Kat Pass
6 S07 Ted Pass
Updated DataFrame...
Id Name Result
0 S Jack Pass
1 S Robin Fail
2 S Ted Pass
3 S Robin Fail
4 S Scarlett Pass
5 S Kat Pass
6 S Ted Pass
คำอธิบาย
\d+คือ Regex pattern ที่จับคู่ตัวเลข 1 หลักขึ้นไปstr.replace()แทนที่ส่วนที่จับคู่ด้วยสตริงว่าง''- ทำงานบน Series (คอลัมน์) ได้โดยตรง