- Head and tail function in Python pandas (Get First N Rows & Last N Rows)
- Loading the iris data set:
- Head Function in Python (Get First N Rows):
- Tail Function in Python (Get Last N Rows):
- Author
- Related Posts:
- Python head Function with Example Program
- What is a Python head?
- Returns
- What is the head () and tail () function?
- Python head list
- df.shape in python
- df.tail() in python
- Summary
- Leave a Comment Cancel reply
- Top 10 функций для анализа данных в Pandas
- 1. read_csv()
- 2. head(), tail()
- 3. info()
- 4. describe()
- 5. dtypes
- 6. astype()
- 7. sample
- 8. drop_duplicates()
- 9. Isna()
- 10. loc[:]
- Pandas – head() and tail() method.
- (B) tail() – select Last N rows of data –
- Share this:
- Like this:
- Leave a Reply Cancel reply
- Newsletter
- Tags
Head and tail function in Python pandas (Get First N Rows & Last N Rows)
In this tutorial we will learn how to get the snap shot of the data, by getting first few rows and last few rows of the data frame i.e Head and Tail function in python. Head function returns first n rows and tail function return last n rows
We will use the iris data set for demonstration of head and tail function in python
Loading the iris data set:
# load iris data set from sklearn import pandas as pd from sklearn import datasets iris=pd.DataFrame(datasets.load_iris().data)
Head Function in Python (Get First N Rows):
# head function in python iris.head()
head function with no arguments gets the first five rows of data from the data frame so the output will be
# head function in python with arguments iris.head(8)
head function with specified N arguments, gets the first N rows of data from the data frame so the output will be
Tail Function in Python (Get Last N Rows):
# Tail function in python iris.tail()
tail function with no arguments gets the last five rows of data from the data frame so the output will be
# tail function in python with arguments iris.tail(8)
tail function with specified N arguments, gets the last N rows of data from the data frame, so the output will be
Author
With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark. View all posts
Related Posts:
Python head Function with Example Program
This tutorial will focus on broadening your knowledge of one of Python’s built-in functions which is the Python head with lots of example programs.
The strong ecosystem of data-centric Python packages makes Python an excellent language for data analysis. Pandas is one of these tools that simplify data import and analysis.
When we say data analysis, it is the action of analyzing data through functions. There are a lot of built-in functions in Python and Pandas packages. One of these is the head() function that enables programmers to analyze if the objects in the program are in the right type of data.
What is a Python head?
In Python programming, the head() function is used to return the first five elements of data frames by default. However, if you want to display a specific number of elements, you may declare an n equal to a certain number (n = 6).
The head() function returns all rows except the last n rows for negative values of n, which is equivalent to df[:-n]. Thus, the value of n will come from the user and the program will display the first n elements (objects).
Python head() function is useful for testing if the objects on your program have the right data type.
Additionally, the head function has the following Syntax, Return Values, and Parameters:
As mentioned beforehand, the n = 5 value is the default, but we can set the value for n specifically.
Returns
Python head() function return values of n from head(n). This n will call the elements of the object’s first row.
For example:
import pandas df = pandas.DataFrame() print(df.head(5))
animal food 0 snake cake 1 bat fried chicken 2 tiger spaghetti 3 lion salad 4 fox asdasd
Explanation
From the example program, the function called the first five elements of two set objects (as assigned in the print function). Take a look at the illustrations below.
The first line of our program reads as:
Moreover, Python does not only have the head() as a built-in function but also has the tail(). You may also learn the Python endswith() function through the Python endswith() Method full tutorial.
What is the head () and tail () function?
Both head() and tail() are Python built-in functions that help programmers with data analysis.
The only difference between the two is that the head() function is applicable for returning the first n values in a row while tail() is for last. Therefore both function works similarly but differs in the position of n (index) of a row.
Python head list
For Python list, the head() function returns the first n values of a list. The number of its output will based on the assigned argument in the program.
However, as mentioned in the above topics, five(5) is the default value of the head() function. This parameter is required so your program will not encounter errors when executed.
df.shape in python
Apart from Python head() and tail(0 functions, you may also use the df.shape in Python. This function returns tuple of the shape of a data frame or series
This Python df.shape function returns a tuple with the number of rows and columns. Additionally, tuples can be unpacked and stored in distinct variables.
df.tail() in python
Python df.tail() function (also known as data frame tail function) is useful in calling the last n values of a list or object. This function can also easily determine the type of data after sorting or data appending.
Python df.tail() Syntax:
Return Value:
Python df.tail() function returns the n value of the last portion of a series or objects (such as list, tuples, etc).
Summary
In summary, the Python head() function is not also usable for calling out the first n elements of a series r objects but also applicable for confirming what type of data is used in that object.
On the other hand, the head function has a corresponding opposite method which works the same with the head but applies at the last portion of a series or data frame. This method is known as the Python tail() function.
Both Python’s head and tail() functions have similarities when referring to how they work. Also, they are opposite particularly in the place where they apply their function.
Nevertheless, the Python head function tutorial has completed the overall topics in learning Python head. This also includes various examples which you can test and apply in your programs.
Hopefully, this tutorial has helped you in your Python programming journey and if you have any suggestions or clarifications, just leave it in the comments.
Leave a Comment Cancel reply
You must be logged in to post a comment.
Top 10 функций для анализа данных в Pandas
Библиотека Pandas предоставляет доступ ко множеству функций, которые могут понадобиться при анализе данных при помощи Python, однако сегодня мы поговорим о 10 функциях, которые должен знать каждый уважающий себя аналитик, использующий Pandas.
Перед работой с функциями Pandas не забываем импортировать эту библиотеку:
1. read_csv()
Функция read_csv() позволяет получить данные из файла формата csv, не используя каких либо сторонних библиотек. Все, что вам нужно сделать – это указать путь до файл. Важно отметить также и то, что данные можно получать как с локального диска, так и из сети Интернет(!). Ниже пример загрузки csv файла c Google диска:
url=’https://drive.google.com/file/d/1KXfupiJKql5Lc-D73KiiS_jEd_CNIW44/view?usp=sharing’
url2=’https://drive.google.com/uc?id=’ + url.split(‘/’)[-2]df = pd.read_csv(url2)
Полученные данные автоматически преобразуются в Dataframe с которым мы и будем работать в дальнейшем.
2. head(), tail()
Функция head() позволяет просмотреть первые пять строк в Dataframe. Вы также можете указать в скобках то количество строк, которые вы хотели бы отобразить с начала Dataframe. Функция tail() работает аналогично, но только вместо первых строк, она показывает последние:
3. info()
Функция info() предоставляет суммарную информацию о вашем Dataframe. Вы получите информацию о количестве строк, наименовании столбцов, количестве непустых строк в них, типе данных в каждом столбце, а также столько памяти занимает Dataframe:
4. describe()
Функция describe() для каждого числового столбца, в случае нашего примера это столбец Rating, выводит основные описательные статистические данные, такие как минимум, максимум, распределение по долям:
5. dtypes
При работе с данными в столбцах, нам необходимо понимать какой формат у этих данных и если Pandas при создании Dataframe неправильно присвоил тип данных столбцу, мы могли бы его в дальнейшем исправить. Функция dtypes() отображает тип данных (обратите внимание, что круглые скобки этой функции при работе в Dataframe не нужны):
6. astype()
Функция astype() позволяет изменить тип данных у столбца в случае, если тип данных некорректный. Для примера воспользуемся примером из одного из предыдущих уроков:
city_data = ‘Город’:[‘Москва’, ‘Казань’, ‘Владивосток’, ‘Санкт-Петербург’, ‘Калининград’],
‘Дата основания’:[‘1147’, ‘1005’, ‘1860’, ‘1703’, ‘1255’],
‘Площадь’:[‘2511’, ‘516’, ‘331’, ‘1439’, ‘223’],
‘Население’:[‘11,9’, ‘1,2’, ‘0,6’, ‘4,9’, ‘0,4’],
‘Погода’:[‘8’, ‘8’, ’17’, ‘9’, ’12’] >
city_df = pd.DataFrame(city_data)
city_df.dtypes
Как вы видите, у столбца Погода тип данных object, хотя в нем вся информация цифровая, давайте переведем его в формат int64:
После преобразования данные в столбце «Погода» стали восприниматься Pandas как int64 и соответственно с ними теперь можно проводить математические операции.
7. sample
Функция sample(n=…) отображает n случайных строк из Dataframe. Великолепная функция, если вам надо ориентировочно понять, что именно содержится в вашем Dataframe. Параметр n отвечает за то, сколько строк необходимо показать:
8. drop_duplicates()
Функция drop_duplicates() удаляет дубликаты в наших данных (параметр inplace=True означает, что мы изменяем исходный Dataframe):
9. Isna()
Функция Isna() возвращает информацию о том, есть ли в вашем Dataframe столбцы с пропущенными данными:
В нашем примере в столбцах Rating, Type, Content Rating, Current Ver, Android Ver есть строки, в которых отсутствуют какие-либо данные.
10. loc[:]
Функция loc позволяет получить данные из выбранных строк и столбцов. В качестве строк необходимо указать номера строк, которые необходимо отразить, а в качестве столбцов – их наименования. К примеру, со второй по четвертую строку получим наименования приложений и их рейтинг:
Хитрость: Используя данную функцию, можно получить данные из конкретной ячейки, указав ее строку и столбец.
Спасибо, за то, что прочитали статью. В ней я хотел рассказать о 10 нужных функциях Pandas при анализе данных, которые должен знать каждый.
В качестве бонуса, как обычно, я прикладываю ноутбук с примерами из этой статьи.
Pandas – head() and tail() method.
By default, the head method returns first 5 rows of data. If you want to return more rows of data then use the n parameter.
# return first 10 rows of data df.head(10)
You can also select few rows of data for a subset of columns using the head method.
# show first 5 rows of alcohol and quality column df[['alcohol','quality']].head()
You can also use the head method to select first n rows of data from a series.
# create a series from df alcohol = df['alcohol'] print("Data Type:",type(alcohol)) # select first 5 rows from a series alcohol.head()
(B) tail() – select Last N rows of data –
To select last N rows of data, we use the tail method in pandas.
# select last 5 rows of data df.tail()
By default, tail also select 5 rows of data but from the last. You can change it using the n parameter.
We can also select last n rows of data from a series.
# select last 4 rows of data from a series alcohol.tail(4)
Share this:
Like this:
Leave a Reply Cancel reply
Newsletter
Tags
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.