Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read only specific columns excel sheet by column name

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")
like image 249
Alex Man Avatar asked Jul 21 '26 00:07

Alex Man


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']]
like image 133
Abhigyan Jaiswal Avatar answered Jul 23 '26 14:07

Abhigyan Jaiswal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!