Pandas DataFrame - Select Multiple Columns by Index


Pandas DataFrame - Select multiple columns by index

To select multiple columns by index in DataFrame in Pandas, you can use iloc property of the DataFrame. DataFrame.iloc property lets us choose required columns based on index from the DataFrame.

The syntax to select required columns by index from a DataFrame df using iloc property is

df.iloc[:, column_indices_list]

You have to replace column_indices_list with the list of column indices.

For example, if you would like to choose the first and third columns of a DataFrame df, then use the following expression.

df.iloc[:,[0, 2]]

: specifies to select all the rows, and [0, 2] specifies to select the columns with index=0 and index=2.

The expressions mentioned above return a DataFrame with the selected columns of the original DataFrame.

Video Tutorial

https://youtu.be/K2IqFZgBLhs?si=253JgwXmn41deGsS

Examples

1. Select columns with index=0 and index=2 from DataFrame using DataFrame.iloc property

To select the columns with index=0 and index=2 in the DataFrame, use the following expression.

df.iloc[:, [0, 2]]

In the following program, we are given a DataFrame in df_1 with three columns: A, B, and C, and five rows. We have to select the columns A and B from the given DataFrame df_1 using iloc property of the DataFrame.

Steps

  1. Given a DataFrame in df_1 with three columns: A, B, and C.
  2. Use iloc property of the DataFrame df_1. Select all the rows, and select the specified columns with index values 0 and 2.
df_1.iloc[:, [0, 2]]
  1. The expression in the above step returns a DataFrame with all the rows and selected columns. Store the returned DataFrame in selected_columns.
  2. You may print the DataFrame selected_columns to output.

Program

Python Program

import pandas as pd

# Take a DataFrame
df_1 = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [5, 10, 15, 20, 25]
})

# Select first and third columns from DataFrame
selected_columns = df_1.iloc[:, [0, 2]]
print(selected_columns)

Output

    A   C
0   2   5
1   4  10
2   6  15
3   8  20
4  10  25

Summary

In this Pandas Tutorial, we learned how to select multiple columns by index from a DataFrame using iloc property of DataFrame instance, with examples.