将excel文件导入python

时间:2017-05-14 13:37:38

标签: python import-from-excel

我有一个关于将xlsx文件导入Python的基本问题。我已经检查了很多关于同一主题的回复,但是无论我尝试什么,我仍然无法将我的文件导入Python。这是我的代码和我收到的错误:

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)

错误:

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

3 个答案:

答案 0 :(得分:8)

使用pandas可以直接获取excel文件的列。这是代码。

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

#print the column names
print df.columns

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

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

答案 1 :(得分:1)

您应该使用raw strings or escape your backslash代替,例如:

file_location = r'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'

file_location = 'C:\\Users\\cagdak\\Desktop\python_self_learning\\Coursera\\sample_data.xlsx'

答案 2 :(得分:0)

继续尝试:

file_location = 'C:/Users/cagdak/Desktop/python_self_learning/Coursera/sample_data.xlsx'