Extract One & Multiple pandas DataFrame Columns by Index in Python (2 Examples)

This tutorial shows how to get one or more variables by index in Python programming.

Preparing the Examples

import pandas as pd                          # Load pandas library
my_df = pd.DataFrame({'A':range(2, 8),       # Construct pandas DataFrame
                      'B':range(22, 16, - 1),
                      'C':['q', 'w', 'e', 'r', 't', 'z'],
                      'D':range(10, 16),
                      'E':['f', 'f', 'g', 'g', 'f', 'f'],
                      'F':range(19, 25)})
print(my_df)
#    A   B  C   D  E   F
# 0  2  22  q  10  f  19
# 1  3  21  w  11  f  20
# 2  4  20  e  12  g  21
# 3  5  19  r  13  g  22
# 4  6  18  t  14  f  23
# 5  7  17  z  15  f  24

Example 1: Selecting a Single pandas DataFrame Column by Index

df_one = my_df.iloc[:, [3]]                  # Extract one column
print(df_one)
#     D
# 0  10
# 1  11
# 2  12
# 3  13
# 4  14
# 5  15

Example 2: Selecting Multiple pandas DataFrame Columns by Index

df_multiple = my_df.iloc[:, [0, 1, 3, 5]]    # Extract multiple columns
print(df_multiple)
#    A   B   D   F
# 0  2  22  10  19
# 1  3  21  11  20
# 2  4  20  12  21
# 3  5  19  13  22
# 4  6  18  14  23
# 5  7  17  15  24

Related Tutorials

Have a look at the following Python tutorials. They focus on topics such as indices and data inspection:

Leave a Reply

Your email address will not be published. Required fields are marked *

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