将excel文件导入python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43964513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
importing an excel file to python
提问by Cagdas Kanar
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:
我有一个关于将 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)
Error:
错误:
IOError: [Errno 2] No such file or directory: 'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
回答by orbit
With pandas it is possible to get directly a column of an excel file. Here is the code.
使用 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]
回答by andy
You should use raw strings or escape your backslashinstead, for example:
您应该使用原始字符串或转义反斜杠,例如:
file_location = r'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
or
或者
file_location = 'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
回答by Stef
go ahead and try this:
继续尝试这个:
file_location = 'C:/Users/cagdak/Desktop/python_self_learning/Coursera/sample_data.xlsx'