นุ่น: วิธีแทรกแถวที่ตำแหน่งดัชนีเฉพาะ
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อแทรกแถวลงในตำแหน่งดัชนีเฉพาะใน DataFrame ของแพนด้า:
#insert row in between index position 2 and 3 df. loc [ 2.5 ] = value1, value2, value3, value4 #sort index df = df. sort_index (). reset_index (drop= True )
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: แทรกแถวที่ตำแหน่งดัชนีเฉพาะใน Pandas
สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ' points ': [18, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print (df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7:28 4 12
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อแทรกบรรทัดระหว่างตำแหน่งดัชนี 2 และ 3:
#insert row in between index position 2 and 3
df. loc [ 2.5 ] = 'Z', 10, 5, 7
#sort index
df = df. sort_index (). reset_index (drop= True )
#view updated DataFrame
print (df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 Z 10 5 7
4 D 14 9 6
5 E 14 12 6
6 F 11 9 5
7 G 20 9 9
8:28 a.m. 4:12
โปรดทราบว่ามีการแทรกบรรทัดระหว่างตำแหน่งดัชนีก่อนหน้า 2 และ 3 โดยมีข้อมูลต่อไปนี้:
- ทีม:Z
- คะแนน: 10
- แอสซิสต์: 5
- รีบาวด์: 7
การใช้ฟังก์ชัน sort_index() และ Reset_index() ทำให้เราสามารถกำหนดค่าให้กับดัชนีใหม่ได้ตั้งแต่ 0 ถึง 8
โปรดทราบว่าแถวใหม่จะต้องมีจำนวนค่าเท่ากับจำนวนคอลัมน์ที่มีอยู่
ตัวอย่างเช่น ถ้าเราพยายามแทรกแถวใหม่โดยมีค่าเพียงสามค่า เราจะได้รับข้อผิดพลาด:
#attempt to insert row with only three values
df. loc [ 2.5 ] = 10, 5, 7
ValueError : cannot set a row with mismatched columns
เราได้รับ ValueError เนื่องจากจำนวนค่าในแถวใหม่ไม่ตรงกับจำนวนคอลัมน์ที่มีอยู่ใน DataFrame
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีแทรกคอลัมน์ลงใน Pandas DataFrame
วิธีเพิ่มแถวใน Pandas DataFrame
วิธีลบแถวใน Pandas DataFrame ตามเงื่อนไข