วิธีสร้างคอลัมน์ที่ซ้ำกันใน pandas dataframe
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อสร้างคอลัมน์ที่ซ้ำกันใน DataFrame ของแพนด้า:
df[' my_column_duplicate '] = df. loc [:, ' my_column ']
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: สร้างคอลัมน์ที่ซ้ำกันใน Pandas DataFrame
สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29, 32], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4, 5], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 8]}) #view DataFrame print (df) points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12 8 32 5 8
เราสามารถใช้โค้ดต่อไปนี้เพื่อสร้าง คอลัมน์ ที่ซ้ำกันและตั้งชื่อว่า point_duplicate :
#create duplicate points column
df[' duplicate_points '] = df. loc [:, ' points ']
#view updated DataFrame
print (df)
points assists rebounds points_duplicate
0 25 5 11 25
1 12 7 8 12
2 15 7 10 15
3 14 9 6 14
4 19 12 6 19
5 23 9 5 23
6 25 9 9 25
7 29 4 12 29
8 32 5 8 32
โปรดทราบว่าคอลัมน์ point_duplicate มีค่าเหมือนกับคอลัมน์ point ทุกประการ
โปรดทราบว่าคอลัมน์ที่ซ้ำกันจะต้องมีชื่อคอลัมน์ที่แตกต่างจากคอลัมน์เดิม มิฉะนั้นจะไม่สร้างคอลัมน์ที่ซ้ำกัน
ตัวอย่างเช่น ถ้าเราลองใช้โค้ดต่อไปนี้เพื่อสร้างคอลัมน์ที่ซ้ำกัน มันจะไม่ทำงาน:
#attempt to create duplicate points column
df[' points '] = df. loc [:, ' points ']
#view updated DataFrame
print (df)
points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12
8 32 5 8
ไม่มีการสร้างคอลัมน์ที่ซ้ำกัน
คอลัมน์ที่ซ้ำกันจะต้องมีชื่อคอลัมน์ที่แตกต่างจากคอลัมน์เดิม
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีพิมพ์ Pandas DataFrame โดยไม่มีดัชนี
วิธีแสดงแถวทั้งหมดใน Pandas DataFrame
วิธีตรวจสอบประเภทของคอลัมน์ทั้งหมดใน Pandas DataFrame