Accessing Last Element Index of pandas DataFrame in Python (4 Examples)
In this article you’ll learn how to select the last element of a pandas DataFrame in the Python programming language.
Preparing the Examples
import pandas as pd # Import pandas library |
import pandas as pd # Import pandas library
my_df = pd.DataFrame({'A':range(11, 17), # Constructing a pandas DataFrame 'B':range(7, 1, - 1), 'C':range(9, 15), 'D':range(10, 16)}) print(my_df) # A B C D # 0 11 7 9 10 # 1 12 6 10 11 # 2 13 5 11 12 # 3 14 4 12 13 # 4 15 3 13 14 # 5 16 2 14 15 |
my_df = pd.DataFrame({'A':range(11, 17), # Constructing a pandas DataFrame 'B':range(7, 1, - 1), 'C':range(9, 15), 'D':range(10, 16)}) print(my_df) # A B C D # 0 11 7 9 10 # 1 12 6 10 11 # 2 13 5 11 12 # 3 14 4 12 13 # 4 15 3 13 14 # 5 16 2 14 15
Example 1: Selecting First Element of Column in pandas DataFrame in Python
ele_f = my_df['C'].iloc[0] # Extracting first column element print(ele_f) # 9 |
ele_f = my_df['C'].iloc[0] # Extracting first column element print(ele_f) # 9
Example 2: Selecting First Row from pandas DataFrame in Python
row_f = my_df.iloc[:1, :] # Extracting first DataFrame row print(row_f) # A B C D # 0 11 7 9 10 |
row_f = my_df.iloc[:1, :] # Extracting first DataFrame row print(row_f) # A B C D # 0 11 7 9 10
Example 3: Selecting Last Element of Column in pandas DataFrame in Python
ele_l = my_df['C'].iloc[len(my_df.index) - 1] # Extracting last column element print(ele_l) # 14 |
ele_l = my_df['C'].iloc[len(my_df.index) - 1] # Extracting last column element print(ele_l) # 14
Example 4: Selecting Last Row from pandas DataFrame in Python
row_l = my_df.iloc[len(my_df.index) - 1:, :] # Extracting last DataFrame row print(row_l) # A B C D # 5 16 2 14 15 |
row_l = my_df.iloc[len(my_df.index) - 1:, :] # Extracting last DataFrame row print(row_l) # A B C D # 5 16 2 14 15
Further Resources & Related Tutorials
Below, you may find some further resources on topics such as indices, naming data, and data inspection.