Pandas is a famous python library that Is extensively used for data processing and analysis in python. In this article we will see how to use the .iloc method which is used for reading selective data from python by filtering both rows and columns from the dataframe.
iloc method processes data by using integer based indexes which may or may not be part of the original data set. The first row is assigned index 0 and second and index 1 and so on. Similarly, the first column is index 0 and second is index 1 and so on.
The Data Set
Below is the data set which we are going to use.
Id SepalLengthCm ... PetalLengthCm PetalWidthCm Iris-setosa-1 5.1 ... 1.4 0.2 Iris-setosa-2 4.9 ... 1.4 0.2 Iris-setosa-3 4.7 ... 1.3 0.2
Selecting rows
We can select both a single row and multiple rows by specifying the integer for the index. In the below example we are selecting individual rows at row 0 and row 1.
Example
import pandas as pd # Create data frame from csv file data = pd.read_csv("D:\\Iris_readings.csv") row0 = data.iloc[0] row1 = data.iloc[1] print(row0) print(row1)
Output
Running the above code gives us the following result −
Id Iris-setosa-1 SepalLengthCm 5.1 SepalWidthCm 3.5 PetalLengthCm 1.4 PetalWidthCm 0.2 Name: 0, dtype: object Id Iris-setosa-2 SepalLengthCm 4.9 SepalWidthCm 3 PetalLengthCm 1.4 PetalWidthCm 0.2 Name: 1, dtype: object
Selecting Multiple Rows
In the below example we select many rows together at one shot by mentioning the slice of the rows we need.
Example
import pandas as pd # making data frame from csv file data = pd.read_csv("D:\\Iris_readings.csv") rows = data.iloc[4:8] print(rows)
Output
Running the above code gives us the following result −
Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm 4 Iris-setosa-5 5.0 3.6 1.4 0.2 5 Iris-versicolor-51 7.0 3.2 4.7 1.4 6 Iris-versicolor-52 6.4 3.2 4.5 1.5 7 Iris-versicolor-53 6.9 3.1 4.9 1.5
Selecting Rows and Columns
In the below example we can select both rows and columns as necessary.
Example
import pandas as pd # making data frame from csv file data = pd.read_csv("D:\\Iris_readings.csv") rows_columns = data.iloc[4:8,0:2] print(rows_columns)
Output
Running the above code gives us the following result −
Id SepalLengthCm 4 Iris-setosa-5 5.0 5 Iris-versicolor-51 7.0 6 Iris-versicolor-52 6.4 7 Iris-versicolor-53 6.9