Select Rows and Columns in Pandas DataFrame using iloc
The iloc[ ] is used for selection based on position. It is similar to loc[] indexer but it takes only integer values to make selections.There are many ways to use this function.
- Select a Single Row
- Select Multiple Rows
- Select Multiple Rows With Some Particular Columns
- Select all the Rows With Some Particular Columns
Select a Single Row
Example : In this example code selects the third row of a DataFrame (df) using integer-location based indexing (.iloc[]) and assigns it to the variable “result.” The last line prints or returns the selected row.
Python3
# Using the operator .iloc[] # to select single row result = df.iloc[ 2 ] # Show the dataframe result |
Output:
Name Aaditya
Age 25
City Mumbai
Salary 40000
Name: 2, dtype: object
Select Multiple Rows
Example : In this example code uses the `.iloc[]` operator to select specific rows (index 2, 3, and 5) from a DataFrame named ‘df’ and assigns the resulting rows to the variable ‘result’. The last line displays the selected rows in the DataFrame.
Python3
# Using the operator .iloc[] # to select multiple rows result = df.iloc[[ 2 , 3 , 5 ]] # Show the dataframe result |
Output:
Name Age City Salary
2 Aaditya 25 Mumbai 40000
3 Saumya 32 Delhi 35000
5 Saumya 32 Mumbai 20000
Select Multiple Rows With Some Particular Columns
Example : In this example code uses the `.iloc[]` operator to select specific rows (2, 3, and 5) and columns (0 and 1) from a DataFrame named `df`, creating a new DataFrame called `result`, and then displays the selected data.
Python3
# Using the operator .iloc[] # to select multiple rows with # some particular columns result = df.iloc[[ 2 , 3 , 5 ], [ 0 , 1 ]] # Show the dataframe result |
Output:
Name Age
2 Aaditya 25
3 Saumya 32
5 Saumya 32
Select all the Rows With Some Particular Columns
Example : In this example code uses the `.iloc[]` operator to select all rows from a DataFrame (`df`) while keeping only the columns at positions 0 and 1, and stores the result in the variable `result`. Finally, it displays the modified DataFrame.
Python3
# Using the operator .iloc[] # to select all the rows with # some particular columns result = df.iloc[:, [ 0 , 1 ]] # Show the dataframe result |
Output:
Name Age
0 Stuti 28
1 Saumya 32
2 Aaditya 25
3 Saumya 32
4 Saumya 32
5 Saumya 32
6 Aaditya 40
7 Seema 32
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection.