在Python-Pandas中使用head()和tail()方法选择数据框架中的第一或最后N行
让我们讨论一下如何使用head()和tail()方法从数据框架中选择顶部或底部的N个行。
1)使用Pandas DataFrame的head()方法从数据框架中选择前N行:
Pandas head()方法用于返回数据框或序列的前n行(默认为5行)。
语法: Dataframe.head(n)
参数:(可选)n是整数值,要返回的行数。
返回:数据框架的前n行
让我们创建一个数据框架
# import pandas library as pd
import pandas as pd
# List of Tuples
students = [('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
输出:

示例 1:
# Show first 5 rows of the details dataframe
# from top
details.head()
输出:

示例 2:
# display top 3 rows of the dataframe
details.head(3)
输出:

示例 3:
# display top 2 rows of the specific columns
details[['Name', 'Age']].head(2)
输出:

2)使用Pandas DataFrame的tail()方法从Dataframe中选择最后N条记录:。
Pandas tail()方法用于返回一个数据框或序列的底部n(默认为5)行。
语法: Dataframe.tail(n)
参数: (optional) n是整数值,要返回的行数。
返回值: 具有底部n行的数据框架。
示例 1:
# Show bottom 5 rows of the dataframe
details.tail()
输出:

示例 2:
# Show bottom 3 rows of the dataframe
details.tail(3)
输出:

示例 3:
# Show bottom 2 rows of the specific
# columns from dataframe
details[['Name', 'Age']].tail(2)
输出:

极客教程