Để lấy hàng thứ n trong Pandas DataFrame, chúng ta có thể sử dụng phương thức iloc(). Ví dụ, df.iloc[4] sẽ trả về hàng thứ 5 vì số hàng bắt đầu từ 0.
Các bước
- Tạo dữ liệu bảng hai chiều,
df. - In DataFrame đầu vào,
df. - Khởi tạo biến
nth_row. - Sử dụng phương thức
iloc()để lấy hàng thứ n. - In DataFrame trả về.
Ví dụ
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)
Kết quả
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