2
votes

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
usecols = ['Col2','Col3']? - rhug123

1 Answers

1
votes

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']]