ในการรับแถวที่ n ใน Pandas DataFrame เราสามารถใช้ iloc() กระบวนการ. ตัวอย่างเช่น df.iloc[4] จะคืนค่าแถวที่ 5 เนื่องจากหมายเลขแถวเริ่มต้นจาก 0
ขั้นตอน
- สร้างข้อมูลตารางแบบสองมิติ ปรับขนาดได้ และอาจต่างกันได้ df.
- พิมพ์อินพุต DataFrame, df.
- เริ่มต้นตัวแปร nth_row
- ใช้วิธี iloc() เพื่อรับแถวที่ n
- พิมพ์ DataFrame ที่ส่งคืน
ตัวอย่าง
import pandas as pd
df = pd.DataFrame(
dict(
name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
marks=[89, 23, 100, 56, 90],
subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
)
)
print "Input DataFrame is:\n", df
nth_row = 3
df = df.iloc[nth_row]
print "Row ", nth_row, "of the DataFrame is: \n", df ผลลัพธ์
Input DataFrame is:
name marks subjects
0 John 89 Math
1 Jacob 23 Physics
2 Tom 100 Chemistry
3 Tim 56 Biology
4 Ally 90 English
Row 3 of the DataFrame is:
name Tim
marks 56
subjects Biology
Name: 3, dtype: object