Select First & Last N Columns from pandas DataFrame in Python (2 Examples)

In this article you’ll learn how to extract the first and last N columns from a pandas DataFrame in Python.

Setting up the Examples

import pandas as pd                         # Load pandas library
my_df = pd.DataFrame({'A':range(10, 17),    # Construct pandas DataFrame
                      'B':range(7, 0, - 1),
                      'C':range(20, 27),
                      'D':range(17, 10, - 1)})
print(my_df)
#     A  B   C   D
# 0  10  7  20  17
# 1  11  6  21  16
# 2  12  5  22  15
# 3  13  4  23  14
# 4  14  3  24  13
# 5  15  2  25  12
# 6  16  1  26  11

Example 1: Extracting the Last N Variables from a pandas DataFrame

my_df_last = my_df.iloc[:, 2:]              # Returning last columns
print(my_df_last)                           # Displaying new DataFrame
#     C   D
# 0  20  17
# 1  21  16
# 2  22  15
# 3  23  14
# 4  24  13
# 5  25  12
# 6  26  11

Example 2: Extracting the First N Variables from a pandas DataFrame

my_df_first = my_df.iloc[:, :2]             # Returning first columns
print(my_df_first)                          # Displaying new DataFrame
#     A  B
# 0  10  7
# 1  11  6
# 2  12  5
# 3  13  4
# 4  14  3
# 5  15  2
# 6  16  1

Related Tutorials & Further Resources

Have a look at the following Python tutorials. They focus on topics such as text elements and extracting data.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top