The Wayback Machine - https://web.archive.org/web/20240930191935/https://www.geeksforgeeks.org/python-basics-of-pandas-using-iris-dataset/
Open In App

Python – Basics of Pandas using Iris Dataset

Last Updated : 20 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python language is one of the most trending programming languages as it is dynamic than others. Python is a simple high-level and an open-source language used for general-purpose programming. It has many open-source libraries and Pandas is one of them. Pandas is a powerful, fast, flexible open-source library used for data analysis and manipulations of data frames/datasets. Pandas can be used to read and write data in a dataset of different formats like CSV(comma separated values), txt, xls(Microsoft Excel) etc. 
In this post, you will learn about various features of Pandas in Python and how to use it to practice.
Prerequisites: Basic knowledge about coding in Python.
Installation:
So if you are new to practice Pandas, then firstly you should install Pandas on your system. 
Go to Command Prompt and run it as administrator. Make sure you are connected with an internet connection to download and install it on your system.
Then type “pip install pandas“, then press Enter key.
 

Download the Dataset “Iris.csv”.
Iris dataset is the Hello World for the Data Science, so if you have started your career in Data Science and Machine Learning you will be practicing basic ML algorithms on this famous dataset. Iris dataset contains five columns such as Petal Length, Petal Width, Sepal Length, Sepal Width and Species Type. 
Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded digitally. 
 

Getting Started with Pandas:
Code: Importing pandas to use in our code as pd.
 

Python3




import pandas as pd


Code: Reading the dataset “Iris.csv”.
 

Python3




data = pd.read_csv("your downloaded dataset location ")



Code: Displaying up the top rows of the dataset with their columns 
The function head() will display the top rows of the dataset, the default value of this function is 5, that is it will show top 5 rows when no argument is given to it.
 

Python3




data.head()


Output: 
 

Displaying the number of rows randomly. 
In sample() function, it will also display the rows according to arguments given, but it will display the rows randomly.
 

Python3




data.sample(10)


Output: 
 

Code: Displaying the number of columns and names of the columns. 
The column() function prints all the columns of the dataset in a list form.
 

Python3




data.columns


Output: 
 

Code: Displaying the shape of the dataset. 
The shape of the dataset means to print the total number of rows or entries and the total number of columns or features of that particular dataset.
 

Python3




#The first one is the number of rows and 
# the other one is the number of columns.
data.shape


Output: 
 

Code: Display the whole dataset
 

Python3




print(data)


Output: 
 

Code: Slicing the rows. 
Slicing means if you want to print or work upon a particular group of lines that is from 10th row to 20th row.
 

Python3




#data[start:end]
#start is inclusive whereas end is exclusive
print(data[10:21])
# it will print the rows from 10 to 20.
  
# you can also save it in a variable for further use in analysis
sliced_data=data[10:21]
print(sliced_data)


Output: 
 

Code: Displaying only specific columns. 
In any dataset, it is sometimes needed to work upon only specific features or columns, so we can do this by the following code.
 

Python3




#here in the case of Iris dataset
#we will save it in a another variable named "specific_data"
  
specific_data=data[["Id","Species"]]
#data[["column_name1","column_name2","column_name3"]]
  
#now we will print the first 10 columns of the specific_data dataframe.
print(specific_data.head(10))


Output: 
 

Filtering:Displaying the specific rows using “iloc” and “loc” functions. 

The “loc” functions use the index name of the row to display the particular row of the dataset. 
The “iloc” functions use the index integer of the row, which gives complete information about the row. 
Code: 
 

Python3




#here we will use iloc
  
data.iloc[5]
#it will display records only with species "Iris-setosa".
data.loc[data["Species"] == "Iris-setosa"]


Output: 
 

iloc()[/caption]
 

loc()

Code: Counting the number of counts of unique values using “value_counts()”. 
The value_counts() function, counts the number of times a particular instance or data has occurred.
 

Python3




#In this dataset we will work on the Species column, it will count number of times a particular species has occurred.
data["Species"].value_counts()
#it will display in descending order.


Output: 
 

Calculating sum, mean and mode of a particular column. 
We can also calculate the sum, mean and mode of any integer columns as I have done in the following code.
 

Python3




# data["column_name"].sum()
  
sum_data = data["SepalLengthCm"].sum()
mean_data = data["SepalLengthCm"].mean()
median_data = data["SepalLengthCm"].median()
  
print("Sum:",sum_data, "\nMean:", mean_data, "\nMedian:",median_data)


Output: 
 

Code: Extracting minimum and maximum from a column. 
Identifying minimum and maximum integer, from a particular column or row can also be done in a dataset.
 

Python3




min_data=data["SepalLengthCm"].min()
max_data=data["SepalLengthCm"].max()
  
print("Minimum:",min_data, "\nMaximum:", max_data)


Output: 
 

Code: Adding a column to the dataset. 
If want to add a new column in our dataset, as we are doing any calculations or extracting some information from the dataset, and if you want to save it a new column. This can be done by the following code by taking a case where we have added all integer values of all columns.
 

Python3




# For example, if we want to add a column let say "total_values", 
# that means if you want to add all the integer value of that particular
# row and get total answer in the new column "total_values".
# first we will extract the columns which have integer values.
cols = data.columns
  
# it will print the list of column names.
print(cols)
  
# we will take that columns which have integer values.
cols = cols[1:5]
  
# we will save it in the new dataframe variable
data1 = data[cols]
  
# now adding new column "total_values" to dataframe data.
data["total_values"]=data1[cols].sum(axis=1)
  
# here axis=1 means you are working in rows, 
# whereas axis=0 means you are working in columns.


Output: 
 

Code: Renaming the columns. 
Renaming our column names can also be possible in python pandas libraries. We have used the rename() function, where we have created a dictionary “newcols” to update our new column names. The following code illustrates that.
 

Python3




newcols={
"Id":"id",
"SepalLengthCm":"sepallength"
"SepalWidthCm":"sepalwidth"}
  
data.rename(columns=newcols,inplace=True)
  
print(data.head())


Output: 
 

Formatting and Styling: 
Conditional formatting can be applied to your dataframe by using Dataframe.style function. Styling is used to visualize your data, and most convenient way of visualizing your dataset is in tabular form. 
Here we will highlight the minimum and maximum from each row and columns.
 

Python3




#this is an example of rendering a datagram, 
which is not visualised by any styles. 
data.style


Output: 
 

Now we will highlight the maximum and minimum column-wise, row-wise, and the whole dataframe wise using Styler.apply function. The Styler.apply function passes each column or row of the dataframe depending upon the keyword argument axis. For column-wise use axis=0, row-wise use axis=1, and for the entire table at once use axis=None.
 

Python3




# we will here print only the top 10 rows of the dataset, 
# if you want to see the result of the whole dataset remove 
#.head(10) from the below code
  
data.head(10).style.highlight_max(color='lightgreen', axis=0)
  
data.head(10).style.highlight_max(color='lightgreen', axis=1)
  
data.head(10).style.highlight_max(color='lightgreen', axis=None)


Output: 
 

for axis=0

 

for axis=1

 

for axis=None

Code: Cleaning and detecting missing values 
In this dataset, we will now try to find the missing values i.e NaN, which can occur due to several reasons.
 

Python3




data.isnull()
#if there is data is missing, it will display True else False.


Output: 
 

isnull()

Code: Summarizing the missing values. 
We will display how many missing values are present in each column.
 

Python3




data.isnull.sum()


Output: 
 

Heatmap: Importing seaborn 
The heatmap is a data visualisation technique which is used to analyse the dataset as colors in two dimensions. Basically it shows correlation between all numerical variables in the dataset. Heatmap is an attribute of the Seaborn library. 
Code: 
 

Python3




import seaborn as sns
  
iris = sns.load_dataset("iris")
sns.heatmap(iris.corr(),camp = "YlGnBu", linecolor = 'white', linewidths = 1)


Output: 
 

Code: Annotate each cell with the numeric value using integer formatting
 

Python3




sns.heatmap(iris.corr(),camp = "YlGnBu", linecolor = 'white', linewidths = 1, annot = True )


Output: 
 

heatmap with annot=True

Pandas Dataframe Correlation: 
Pandas correlation is used to determine pairwise correlation of all the columns of the dataset. In dataframe.corr(), the missing values are excluded and non-numeric columns are also ignored. 
Code: 
 

Python3




data.corr(method='pearson')


Output: 
 

data.corr()

The output dataframe can be seen as for any cell, row variable correlation with the column variable is the value of the cell. The correlation of a variable with itself is 1. For that reason, all the diagonal values are 1.00.
Multivariate Analysis: 
Pair plot is used to visualize the relationship between each type of column variable. It is implemented only by one line code, which is as follows : 
Code: 
 

Python3




g = sns.pairplot(data,hue="Species")


Output: 
 

Pairplot of variable “Species”, to make it more understandable.

 



Similar Reads

Analyzing Decision Tree and K-means Clustering using Iris dataset
Iris Dataset is one of best know datasets in pattern recognition literature. This dataset contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2 the latter are NOT linearly separable from each other. Attribute Information:Sepal Length in cmSepal Width in cmPetal Len
5 min read
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand
2 min read
Comparison of LDA and PCA 2D projection of Iris dataset in Scikit Learn
LDA and PCA both are dimensionality reduction techniques in which we try to reduce the dimensionality of the dataset without losing much information and preserving the pattern present in the dataset. In this article, we will use the iris dataset along with scikit learn pre-implemented functions to perform LDA and PCA with a single line of code. Con
3 min read
How can Tensorflow be used with Estimators to split the iris dataset?
TensorFlow is an open-source machine-learning framework that has become incredibly popular in the past few years. It is widely used for building and training deep neural networks, as well as for implementing other machine learning algorithms. Estimators, on the other hand, are high-level TensorFlow APIs that can be used to simplify the process of b
5 min read
Gaussian Process Classification (GPC) on Iris Dataset
A potent machine learning approach that may be used for both regression and classification problems is Gaussian process classification or GPC. It is predicated on the notion of using a probabilistic model that depicts a distribution across functions, known as a Gaussian process. Using this distribution, one may forecast a function's output given a
7 min read
Decision Boundary of Label Propagation Vs SVM on the Iris Dataset
In machine learning, understanding decision boundaries is crucial for classification tasks. The decision boundary separates different classes in a dataset. Here, we'll explore and compare decision boundaries generated by two popular classification algorithms - Label Propagation and Support Vector Machines (SVM) - using the famous Iris dataset in Py
9 min read
Project | kNN | Classifying IRIS Dataset
Introduction | kNN Algorithm Statistical learning refers to a collection of mathematical and computation tools to understand data.In what is often called supervised learning, the goal is to estimate or predict an output based on one or more inputs.The inputs have many names, like predictors, independent variables, features, and variables being call
8 min read
How to get a cartesian product of a huge Dataset using Pandas in Python?
In this article, we will discuss how to do a cartesian product of a huge Dataset. The function which we are using here to do cartesian product is the merge function which is the entry point for all standard database join operations between DataFrame objects. Syntax: data1 = pd.DataFrame({'dataset_name_1': [dataset_1]}) data2 = pd.DataFrame({'datase
2 min read
How To Convert Sklearn Dataset To Pandas Dataframe In Python
In this article, we look at how to convert sklearn dataset to a pandas dataframe in Python. Sklearn and pandas are python libraries that are used widely for data science and machine learning operations. Pandas is majorly focused on data processing, manipulation, cleaning, and visualization whereas sklearn library provides a vast list of tools and f
3 min read
Box plot and Histogram exploration on Iris data
Attribute Information about data set: Attribute Information: -> sepal length in cm -> sepal width in cm -> petal length in cm -> petal width in cm -> class: Iris Setosa Iris Versicolour Iris VirginicaNumber of Instances: 150 Summary Statistics: Min Max Mean SD Class Correlation sepal length: 4.3 7.9 5.84 0.83 0.7826 sepal width: 2.0
2 min read
How to split a Dataset into Train and Test Sets using Python
Here we will discuss how to split a dataset into Train and Test sets in Python. The train-test split is used to estimate the performance of machine learning algorithms that are applicable for prediction-based Algorithms/Applications. This method is a fast and easy procedure to perform such that we can compare our own machine learning model results
3 min read
How can Tensorflow be used to download and explore the Iliad dataset using Python?
Tensorflow is a free open-source machine learning and artificial intelligence library widely popular for training and deploying neural networks. It is developed by Google Brain Team and supports a wide range of platforms. In this tutorial, we will learn to download, load and explore the famous Iliad dataset. In the Iliad dataset, there are various
2 min read
ML | Using SVM to perform classification on a non-linear dataset
Prerequisite: Support Vector Machines Definition of a hyperplane and SVM classifier: For a linearly separable dataset having n features (thereby needing n dimensions for representation), a hyperplane is basically an (n - 1) dimensional subspace used for separating the dataset into two sets, each set containing data points belonging to a different c
4 min read
Pyspark | Linear regression with Advanced Feature Dataset using Apache MLlib
Ames Housing Data: The Ames Housing dataset was compiled by Dean De Cock for use in data science education and expanded version of the often-cited Boston Housing dataset. The dataset provided has 80 features and 1459 instances. Dataset description is as below: For demo few columns are displayed but there are a lot more columns are there in the data
4 min read
MNIST Dataset : Practical Applications Using Keras and PyTorch
The MNIST dataset is a popular dataset used for training and testing in the field of machine learning for handwritten digit recognition. The article aims to explore the MNIST dataset, its characteristics and its significance in machine learning. Table of Content What is MNIST Dataset?Structure of MNIST datasetOrigin of the MNIST DatasetMethods to l
8 min read
Python - Removing Constant Features From the Dataset
Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don't provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove th
2 min read
Sklearn Diabetes Dataset : Scikit-learn Toy Datasets in Python
The Sklearn Diabetes Dataset typically refers to a dataset included in the scikit-learn machine learning library, which is a synthetic dataset rather than real-world data. This dataset is often used for demonstration purposes in machine learning tutorials and examples. In this article, we are going to learn more about the Sklearn Diabetes Dataset,
5 min read
Python | pandas.to_markdown() in Pandas
With the help of pandas.to_markdown() method, we can get the markdown table from the given dataframes by using pandas.to_markdown() method. Syntax : pandas.to_markdown() Return : Return the markdown table. Example #1 : In this example we can see that by using pandas.to_markdown() method, we are able to get the markdown table from the given datafram
1 min read
Python Pandas - pandas.api.types.is_file_like() Function
In this article, we will be looking toward the functionality of pandas.api.types.is_file_like() from the pandas.api.types module with its various examples in the Python language. An object must be an iterator AND have a read or write method as an attribute to be called file-like. It is important to note that file-like objects must be iterable, but
2 min read
Importing Kaggle dataset into google colaboratory
While building a Deep Learning model, the first task is to import datasets online and this task proves to be very hectic sometimes. We can easily import Kaggle datasets in just a few steps: Code: Importing CIFAR 10 dataset !pip install kaggle Now go to your Kaggle account and create new API token from my account section, a kaggle.json file will be
1 min read
Different dataset forms in Social Networks
Prerequisite: Python Basics For constructing any network we need a good dataset and every network has a different format for data of datasets. Basically a dataset is nothing but a huge collection of data that can be used further for any analysis. Data in dataset can be in many formats. Example of Network datasets: Ingredients network.Synonymy netwo
3 min read
Visualising ML DataSet Through Seaborn Plots and Matplotlib
Working on data can sometimes be a bit boring. Transforming a raw data into an understandable format is one of the most essential part of the whole process, then why to just stick around on numbers, when we can visualize our data into mind-blowing graphs which are up for grabs in python. This article will focus on exploring plots which could make y
7 min read
What is Supervised Dataset in PyBrain?
In this article, we will be looking at the various uses and functionality of the supervised dataset in Pybrain. A Dataset is a collection of data where we do give the list of values to each member belonging to the dataset. A supervised dataset following supervised learning has input and output fields. In this example, we will learn how to use a Sup
2 min read
KMeans Clustering and PCA on Wine Dataset
K-Means Clustering: K Means Clustering is an unsupervised learning algorithm that tries to cluster data based on their similarity. Unsupervised learning means that there is no outcome to be predicted, and the algorithm just tries to find patterns in the data. In k means clustering, we specify the number of clusters we want the data to be grouped in
6 min read
How can Tensorflow be used to load the flower dataset and work with it?
Tensorflow flower dataset is a large dataset of images of flowers. In this article, we are going to see, how we can use Tensorflow to load the flower dataset and work with it. Let us start by importing the necessary libraries. Here we are going to use the tensorflow_dataset library to load the dataset. It is a library of public datasets ready to us
4 min read
Gaussian Process Classification (GPC) on the XOR Dataset in Scikit Learn
Gaussian process classification (GPC) is a probabilistic approach to classification that models the conditional distribution of the class labels given the feature values. In GPC, the data is assumed to be generated by a Gaussian process, which is a stochastic process that is characterized by its mean and covariance functions. The mean function in G
4 min read
How can Tensorflow be used to configure the dataset for performance?
Tensorflow is a popular open-source platform for building and training machine learning models. It provides several techniques for loading and preparing the dataset to get the best performance out of the model. The correct configuration of the dataset is crucial for the overall performance of the model, so it is important to choose the right techni
8 min read
HuberRegressor vs Ridge on Dataset with Strong Outliers in Scikit Learn
Regression is a commonly used machine learning technique for predicting continuous outputs. In some datasets, outliers can have a significant impact on the results. To handle such datasets with outliers, two common algorithms are Huber Regressor and Ridge Regression. This article will explore the differences between the two algorithms in the contex
7 min read
How to upload a dataset in Jupyter Notebook?
Jupyter Notebook is a web-based powerful IDE tool that helps with data analysis, visualization and narrative multi-media. Uploading a dataset is a very common task when working in the Jupyter Notebook. It is widely used by data analysts, data scientists, researchers and other developers to perform data analysis, machine learning tasks and other sci
4 min read
How to Load a Dataset From the Google Drive to Google Colab
Users can code in Python using Google's free Colab (short for Collaboratory) platform. It is a Google cloud service that uses Jupyter Notebook. With the help of this platform, we can easily and for free train machine learning models in the cloud. With Google Colab, you can use GPU and TPU for nothing, just like your Jupyter Notebook can. Quick inst
4 min read