เพื่อหาแถวที่ 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