Выберите первые или последние N строк в Dataframe с помощью методов head () и tail () в Python-Pandas
Давайте обсудим, как выбрать верхнее или нижнее количество N строк из Dataframe с помощью методов head () и tail ().
1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame :
Pandas head() method is used to return top n (5 by default) rows of a data frame or series
Syntax: Dataframe.head(n).
Parameters: (optional) n is integer value, number of rows to be returned.
Return: Dataframe with top n rows .
Let’s Create a dataframe
# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [("Ankit", 22, "Up", "Geu"), ("Ankita", 31, "Delhi", "Gehu"), ("Rahul", 16, "Tokyo", "Abes"), ("Simran", 41, "Delhi", "Gehu"), ("Shaurya", 33, "Delhi", "Geu"), ("Harshita", 35, "Mumbai", "Bhu" ), ("Swapnil", 35, "Mp", "Geu"), ("Priya", 35, "Uk", "Geu"), ("Jeet", 35, "Guj", "Gehu"), ("Ananya", 35, "Up", "Bhu") ] # Create a DataFrame object from# list of tuples along with columns# and indices.details = pd.DataFrame(students, columns =["Name", "Age", "Place", "College"], index =["a", "b", "c", "d", "e", "f", "g", "i", "j", "k"]) details |
Выход:

Example 1:
# Show first 5 rows of the details dataframe# from topdetails.head() |
Output:

Example 2:
# display top 3 rows of the dataframedetails.head(3) |
Output:

Example 3:
# display top 2 rows of the specific columnsdetails[["Name", "Age"]].head(2) |
Выход:

2) Выберите последние N строк из фрейма данных, используя метод tail () фрейма данных Pandas:
Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series.
Syntax: Dataframe.tail(n)
Parameters: (optional) n is integer value, number of rows to be returned.
Return: Dataframe with bottom n rows .
Example 1:
# Show bottom 5 rows of the dataframedetails.tail() |
Output:

Example 2:
# Show bottom 3 rows of the dataframedetails.tail(3) |
Output:

Example 3:
# Show bottom 2 rows of the specific# columns from dataframedetails[["Name", "Age"]].tail(2) |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.