Python Subset Multiple Columns of Pandas DataFrame (Example Code)

In this Python post you’ll learn how to extract variables of pandas DataFrame.

Example Data

import pandas as pd                          # Load pandas
my_df = pd.DataFrame({'A':range(10, 15),    # Constructing example data
                      'B':["x", "c", "e", "y", "i"],
                      'C':range(100, 105)})
print(my_df)                                # Displaying example data in Python console
#     A  B    C
# 0  10  x  100
# 1  11  c  101
# 2  12  e  102
# 3  13  y  103
# 4  14  i  104

Example: Subsetting Columns of pandas DataFrame

my_df = my_df[['A', 'C']]                   # Extract columns from data
print(my_df)                                # Displaying updated data
#     A    C
# 0  10  100
# 1  11  101
# 2  12  102
# 3  13  103
# 4  14  104

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