In this post, I am going to explain how to access the DataFrame rows using index position.
I am going to use below dataset to demonstrate the examples.
Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89
As per the above data set,
a. row with index 0 point to the person ‘Krishna’ details
b. Row with 1 point to the person ‘Sailu’ details etc.,
How to access a row at index 0?
Using df.iloc[index_location], we can access the row at index 0.
row_at_1st_position = df.iloc[0]
How to access multiple rows at a time?
By passing the list of index locations to the iloc accessor, we can access multiple rows.
rows_at_2nd_4th_positions = df.iloc[[2, 4]]
Above statement extract the rows at indexes 2nd and 4th positions.
You will get ‘IndexError’, when trying to access the index which is out of bounds.
Find the below working application.
iloc_hello_world.py
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
'Age': [34, 35, 29, 35, 52, 34],
'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
'Rating': [81, 76, 67, 100, 87, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)
row_at_1st_position = df.iloc[0]
row_at_2nd_position = df.iloc[1]
print('\nrow_at_1st_position : \n', row_at_1st_position)
print('\nrow_at_2nd_position : \n', row_at_2nd_position)
rows_at_2nd_4th_positions = df.iloc[[2, 4]]
print('\nrows_at_2nd_4th_positions: \n', rows_at_2nd_4th_positions)
try:
print('\nTrying to access the element at index 10')
print(df.iloc[10])
except IndexError as e:
print(e)
Output
Original DataFrame Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 row_at_1st_position : Name Krishna Age 34 City Bangalore Gender Male Rating 81 Name: 0, dtype: object row_at_2nd_position : Name Sailu Age 35 City Hyderabad Gender Female Rating 76 Name: 1, dtype: object rows_at_2nd_4th_positions: Name Age City Gender Rating 2 Joel 29 Hyderabad Male 67 4 Jitendra 52 Bangalore Male 87 Trying to access the element at index 10 single positional indexer is out-of-bounds
Following are the common use cases of iloc accessor.
a. Accessing Rows and Columns
b. Slicing
c. Assigning values
Accessing rows and columns
In Pandas, both row and column indexes will start from 0.
Example 1: Access a single row by its integer index
df.iloc[row_index_1]
Example 2: Access multiple rows by their integer indices
df.iloc[[row_index_1, row_index_2]]
Example 3: Access specific column of the row
df.iloc[row_index_1, column_index_1]
Example 4: Access specific columns of the row
df.iloc[row_index_1, [column_index_1, column_index_2]]
Example 5: Access multiple rows and columns
df.iloc[[row_index_1, row_index_2], [column_index_1, column_index_2]]
access_rows_columns.py
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
'Age': [34, 35, 29, 35, 52, 34],
'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
'Rating': [81, 76, 67, 100, 87, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)
row_index_1 = 2
row_index_2 = 4
column_index_1 = 0
column_index_2 = 2
# Access a single row by its integer index
result = df.iloc[row_index_1]
print('\nAccess a single row by its integer index :\n', result)
# Access multiple rows by their integer indices
result = df.iloc[[row_index_1, row_index_2]]
print('\nAccess multiple rows by their integer indices :\n', result)
# Access specific column of the row
result = df.iloc[row_index_1, column_index_1]
print('\nAccess specific column of the row :\n', result)
# Access specific columns of the row
result = df.iloc[row_index_1, [column_index_1, column_index_2]]
print('\nAccess specific columns of the row :\n', result)
# Access multiple rows and columns
result = df.iloc[[row_index_1, row_index_2], [column_index_1, column_index_2]]
print('\nAccess multiple rows and columns :\n', result)
Output
Original DataFrame Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 Access a single row by its integer index : Name Joel Age 29 City Hyderabad Gender Male Rating 67 Name: 2, dtype: object Access multiple rows by their integer indices : Name Age City Gender Rating 2 Joel 29 Hyderabad Male 67 4 Jitendra 52 Bangalore Male 87 Access specific column of the row : Joel Access specific columns of the row : Name Joel City Hyderabad Name: 2, dtype: object Access multiple rows and columns : Name City 2 Joel Hyderabad 4 Jitendra Bangalore
Slicing
Example 1: Slice rows based on integer indices
df.iloc[row_start_index:row_end_index]
Example 2: Access all the rows from starting to row_end_index (end index is exclusive)
df.iloc[:row_end_index]
Example 3: Access all the rows from row_start_index to end
df.iloc[row_start_index:]
Example 4: Slice rows based on integer indices and a step of step_count
df.iloc[row_start_index:row_end_index:step_count]
Example 5: Slice rows and select specific columns
df.iloc[row_start_index:row_end_index, column_start_index:column_end_index]
Example 6: Access all rows for specific column
df.iloc[:, column_index]
Example 7: Access all rows for specific columns
df.iloc[:, [column_index_1, column_index_2]]
slicing.py
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
'Age': [34, 35, 29, 35, 52, 34],
'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
'Rating': [81, 76, 67, 100, 87, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)
row_start_index = 1
row_end_index = 5
step_count = 2
column_start_index = 0
column_end_index = 3
column_index = 0
column_index_1 = 0
column_index_2 = 2
# Slice rows based on integer indices
result = df.iloc[row_start_index:row_end_index]
print('\nSlice rows based on integer indices\n', result)
# Access all the rows from starting to row_end_index
result = df.iloc[:row_end_index]
print('\nAccess all the rows from starting to row_end_index\n', result)
# Access all the rows from row_start_index to end
result = df.iloc[row_start_index:]
print('\nAccess all the rows from row_start_index to end\n', result)
# Slice rows based on integer indices and a step of step_count
result = df.iloc[row_start_index:row_end_index:step_count]
print('\nSlice rows based on integer indices and a step of step_count\n', result)
# Slice rows and select specific columns
result = df.iloc[row_start_index:row_end_index, column_start_index:column_end_index]
print('\nSlice rows and select specific columns\n', result)
# Access all rows for specific column
result = df.iloc[:, column_index]
print('\nAccess all rows for specific column\n', result)
# Access all rows for specific columns
result = df.iloc[:, [column_index_1, column_index_2]]
print('\nAccess all rows for specific columns\n', result)
Output
Original DataFrame Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 Slice rows based on integer indices Name Age City Gender Rating 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 Access all the rows from starting to row_end_index Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 Access all the rows from row_start_index to end Name Age City Gender Rating 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 Slice rows based on integer indices and a step of step_count Name Age City Gender Rating 1 Sailu 35 Hyderabad Female 76 3 Chamu 35 Chennai Female 100 Slice rows and select specific columns Name Age City 1 Sailu 35 Hyderabad 2 Joel 29 Hyderabad 3 Chamu 35 Chennai 4 Jitendra 52 Bangalore Access all rows for specific column 0 Krishna 1 Sailu 2 Joel 3 Chamu 4 Jitendra 5 Raj Name: Name, dtype: object Access all rows for specific columns Name City 0 Krishna Bangalore 1 Sailu Hyderabad 2 Joel Hyderabad 3 Chamu Chennai 4 Jitendra Bangalore 5 Raj Chennai
Assigning Values
Example 1: Assign a value to a specific cell
df.iloc[row_index, column_index] = 'Harika'
Example 2: Assign a value to multiple cells based on a condition
df.iloc[df['City'] == 'Hyderabad', column_index] = 'Mumbai'
assign_values.py
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
'Age': [34, 35, 29, 35, 52, 34],
'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
'Rating': [81, 76, 67, 100, 87, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)
row_index = 1
column_index = 0
# Assign a value to a specific cell
print('\nSet the Name of row index 1 to Harika')
df.iloc[row_index, column_index] = 'Harika'
print(df)
# Assign a value to multiple cells based on a condition
column_index = 2
print('\nSet the city of all the people living in Hyderabad to Mumbai')
df.iloc[df['City'] == 'Hyderabad', column_index] = 'Mumbai'
print(df)
Output
Original DataFrame Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Sailu 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 Set the Name of row index 1 to Harika Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Harika 35 Hyderabad Female 76 2 Joel 29 Hyderabad Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89 Set the city of all the people living in Hyderabad to Mumbai Name Age City Gender Rating 0 Krishna 34 Bangalore Male 81 1 Harika 35 Mumbai Female 76 2 Joel 29 Mumbai Male 67 3 Chamu 35 Chennai Female 100 4 Jitendra 52 Bangalore Male 87 5 Raj 34 Chennai Male 89
No comments:
Post a Comment