Pandas: วิธีเพิ่มคำนำหน้าชื่อคอลัมน์
คุณสามารถใช้วิธีการต่อไปนี้เพื่อใส่คำนำหน้าชื่อคอลัมน์ใน Pandas DataFrame:
วิธีที่ 1: เพิ่มคำนำหน้าให้กับชื่อคอลัมน์ทั้งหมด
df = df. add_prefix (' my_prefix_ ')
วิธีที่ 2: เพิ่มคำนำหน้าให้กับชื่อคอลัมน์ที่ระบุ
#specify columns to add prefix to cols = [' col1 ', ' col3 '] #add prefix to specific columns df = df. rename (columns={c: ' my_prefix_ '+c for c in df. columns if c in cols})
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีเหล่านี้กับ Pandas DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23], ' assists ': [5, 7, 7, 9, 12, 9], ' rebounds ': [11, 8, 10, 6, 6, 5], ' blocks ': [6, 6, 3, 2, 7, 9]}) #view DataFrame print (df) points assists rebounds blocks 0 25 5 11 6 1 12 7 8 6 2 15 7 10 3 3 14 9 6 2 4 19 12 6 7 5 23 9 5 9
วิธีที่ 1: เพิ่มคำนำหน้าให้กับชื่อคอลัมน์ทั้งหมด
รหัสต่อไปนี้แสดงวิธีการเพิ่มคำนำหน้า “_total” ให้กับชื่อคอลัมน์ทั้งหมด:
#add 'total_' as prefix to each column name df = df. add_prefix (' total_ ') #view updated DataFrame print (df) total_points total_assists total_rebounds total_blocks 0 25 5 11 6 1 12 7 8 6 2 15 7 10 3 3 14 9 6 2 4 19 12 6 7 5 23 9 5 9
โปรดทราบว่ามีการเพิ่มคำนำหน้า “_total” ให้กับชื่อคอลัมน์ทั้งหมดแล้ว
วิธีที่ 2: เพิ่มคำนำหน้าให้กับชื่อคอลัมน์ที่ระบุ
รหัสต่อไปนี้แสดงวิธีการเพิ่มคำนำหน้า “total_” เฉพาะคอลัมน์ point และ Assists :
#specify columns to add prefix to cols = [' points ', ' assists '] #add _'total' as prefix to specific columns df = df. rename (columns={c: ' total_ '+c for c in df.columns if c in cols}) #view updated DataFrame print (df) total_points total_assists rebounds blocks 0 25 5 11 6 1 12 7 8 6 2 15 7 10 3 3 14 9 6 2 4 19 12 6 7 5 23 9 5 9
โปรดทราบว่ามีการเพิ่มคำนำหน้า ‘total_’ ในคอลัมน์ คะแนน และคอลัมน์ สนับสนุน เท่านั้น
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีลบคอลัมน์ใน Pandas
วิธีแยกคอลัมน์ใน Pandas
วิธีเปลี่ยนลำดับคอลัมน์ใน Pandas
วิธีใช้ฟังก์ชันกับคอลัมน์ที่เลือกใน Pandas