Delete First & Last N Columns from pandas DataFrame in Python (2 Examples)
In this tutorial you’ll learn how to remove the first and last N variables from a pandas DataFrame in Python programming.
Setting up 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, 5), # Construct pandas DataFrame 'B':range(5, 1, - 1), 'C':range(10, 14), 'D':range(20, 24), 'E':range(0, 4), 'F':range(17, 13, - 1)}) print(my_df) # A B C D E F # 0 1 5 10 20 0 17 # 1 2 4 11 21 1 16 # 2 3 3 12 22 2 15 # 3 4 2 13 23 3 14 |
my_df = pd.DataFrame({'A':range(1, 5), # Construct pandas DataFrame 'B':range(5, 1, - 1), 'C':range(10, 14), 'D':range(20, 24), 'E':range(0, 4), 'F':range(17, 13, - 1)}) print(my_df) # A B C D E F # 0 1 5 10 20 0 17 # 1 2 4 11 21 1 16 # 2 3 3 12 22 2 15 # 3 4 2 13 23 3 14
Example 1: Removing the First N Variables from a pandas DataFrame
my_df_last = my_df.iloc[:, 2:] # Returning last columns print(my_df_last) # C D E F # 0 10 20 0 17 # 1 11 21 1 16 # 2 12 22 2 15 # 3 13 23 3 14 |
my_df_last = my_df.iloc[:, 2:] # Returning last columns print(my_df_last) # C D E F # 0 10 20 0 17 # 1 11 21 1 16 # 2 12 22 2 15 # 3 13 23 3 14
Example 2: Removing the Last N Variables from a pandas DataFrame
my_df_first = my_df.iloc[:, :4] # Returning first columns print(my_df_first) # A B C D # 0 1 5 10 20 # 1 2 4 11 21 # 2 3 3 12 22 # 3 4 2 13 23 |
my_df_first = my_df.iloc[:, :4] # Returning first columns print(my_df_first) # A B C D # 0 1 5 10 20 # 1 2 4 11 21 # 2 3 3 12 22 # 3 4 2 13 23
Related Articles & Further Resources
Have a look at the following Python tutorials. They focus on similar topics as this post:
- Ordering pandas DataFrame Rows by Multiple Columns in Python
- Number of Rows, Columns & Dimensions of pandas DataFrame in Python
- Mean Imputation of Columns in pandas DataFrame in Python
- Rearrange Columns of pandas DataFrame in Python
- Join Text of Two Columns in pandas DataFrame in Python
- Get Top & Bottom N Rows of pandas DataFrame in Python