Python read only specific columns excel sheet by column name

Viewed 436

I have an excel sheet contains many columns.

Col1 Col2 Col3
  1    2     A
  2    2     B
  3    2     B

I am using pandas read_excel and use "usecols" to read a column by its index. Just wondering if there is any way to read those columns by their name instead? For instance, in this example Col2 and Col3?

import pandas as pd
df = pd.read_excel(file_path, sheet_name=sheet_name, usecols="A,C")
1 Answers

If you want Col2 and Col3 the you can use the following code:

import pandas as pd

df = pd.read_excel(file_path, sheet_name=sheet_name, usecols = ['Col2','Col3'])

or you can use this:

import pandas as pd

df = pd.read_excel(file_path, sheet_name=sheet_name)[['Col2', 'Col3']]
Related