将excel文件导入python

问题描述 投票:3回答:3

我有一个关于将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'
python import-from-excel
3个回答
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
投票

您应该使用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'

0
投票

继续尝试这个:

file_location = 'C:/Users/cagdak/Desktop/python_self_learning/Coursera/sample_data.xlsx'
© www.soinside.com 2019 - 2024. All rights reserved.