Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - How to select rows from a DataFrame by integer location
To select rows by integer location in a Pandas DataFrame, use the iloc accessor. The iloc method allows you to select rows and columns by their integer position, starting from 0.
Creating a Sample DataFrame
Let's start by creating a DataFrame to work with ?
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
print("DataFrame...")
print(dataFrame)
DataFrame...
a b
x 10 15
y 20 25
z 30 35
Selecting a Single Row by Integer Location
Use iloc[index] to select a single row by its integer position ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
# Select row at integer location 1 (second row)
print("Select row by integer location 1:")
print(dataFrame.iloc[1])
Select row by integer location 1: a 20 b 25 Name: y, dtype: int64
Selecting Multiple Rows
You can select multiple rows by passing a list of integer positions ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
# Select rows at positions 0 and 2
print("Select multiple rows by integer location:")
print(dataFrame.iloc[[0, 2]])
Select multiple rows by integer location:
a b
x 10 15
z 30 35
Using Slicing with iloc
You can also use slicing to select a range of rows ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
# Select rows from position 0 to 1 (exclusive of 2)
print("Select rows using slice notation:")
print(dataFrame.iloc[0:2])
Select rows using slice notation:
a b
x 10 15
y 20 25
Comparison: iloc vs loc
| Method | Selection Type | Example |
|---|---|---|
iloc |
Integer position | df.iloc[1] |
loc |
Label-based | df.loc['y'] |
Conclusion
Use iloc to select rows by integer position in a DataFrame. It supports single row selection, multiple rows with lists, and range selection with slicing notation.
Advertisements
