Remove First & Last N Rows from pandas DataFrame in Python (2 Examples)
In this post you’ll learn how to delete the first and last N rows from a pandas DataFrame in Python.
Preparing the Examples
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':range(1, 7), # Constructing a pandas DataFrame 'B':range(7, 1, - 1), 'C':range(8, 14), 'D':range(0, 6), 'E':range(17, 11, - 1)}) print(my_df) # A B C D E # 0 1 7 8 0 17 # 1 2 6 9 1 16 # 2 3 5 10 2 15 # 3 4 4 11 3 14 # 4 5 3 12 4 13 # 5 6 2 13 5 12 |
my_df = pd.DataFrame({'A':range(1, 7), # Constructing a pandas DataFrame 'B':range(7, 1, - 1), 'C':range(8, 14), 'D':range(0, 6), 'E':range(17, 11, - 1)}) print(my_df) # A B C D E # 0 1 7 8 0 17 # 1 2 6 9 1 16 # 2 3 5 10 2 15 # 3 4 4 11 3 14 # 4 5 3 12 4 13 # 5 6 2 13 5 12
Example 1: Removing the First N Rows from a pandas DataFrame
my_df_first = my_df.iloc[4:] # Drop first rows print(my_df_first) # A B C D E # 4 5 3 12 4 13 # 5 6 2 13 5 12 |
my_df_first = my_df.iloc[4:] # Drop first rows print(my_df_first) # A B C D E # 4 5 3 12 4 13 # 5 6 2 13 5 12
Example 2: Removing the Last N Rows from a pandas DataFrame
my_df_last = my_df.iloc[:3] # Drop last rows print(my_df_last) # A B C D E # 0 1 7 8 0 17 # 1 2 6 9 1 16 # 2 3 5 10 2 15 |
my_df_last = my_df.iloc[:3] # Drop last rows print(my_df_last) # A B C D E # 0 1 7 8 0 17 # 1 2 6 9 1 16 # 2 3 5 10 2 15
Further Resources & Related Tutorials
In addition, you might have a look at the other tutorials on my website. I have released several articles on topics such as indices, extracting data, counting, and descriptive statistics:
- Extract Values of First Row in pandas DataFrame in Python
- Order Rows of pandas DataFrame by Column in Python
- How to Reverse Rows of pandas DataFrame in Python
- Extract Rows of pandas DataFrame by Indices in Python
- Ordering pandas DataFrame Rows by Multiple Columns in Python
- Drop Rows with NaN in pandas DataFrame Column in Python