importing an excel file to python

Cagdas Kanar picture Cagdas Kanar · May 14, 2017 · Viewed 71.7k times · Source

I have a basic question about importing xlsx files to Python. I have checked many responses about the same topic, however I still cannot import my files to Python whatever I try. Here's my code and the error I receive:

import pandas as pd

import xlrd

file_location = 'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
workbook = xlrd.open_workbook(file_location)

Error:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\cagdak\\Desktop\\python_self_learning\\Coursera\\sample_data.xlsx'

Answer

orbit picture orbit · May 14, 2017

With pandas it is possible to get directly a column of an Excel file. Here is the code.

import pandas
df = pandas.read_excel('sample.xls')

#print the column names
print df.columns

#get the values for a given column
values = df['column_name'].values

#get a data frame with selected columns
FORMAT = ['Col_1', 'Col_2', 'Col_3']
df_selected = df[FORMAT]