我有一个包含27列的excel文件。我想编写一个逐列读取的python代码,并将最后的5个值存储在coloum中,这些值将对它们进行数学方程式。
到目前为止,我有这个:
from math import tan
#Write Header
#outFile.write('Test Name,X+ avg,X+ std,X+ count,X- avg,X- std,X- count,X angle,Y+ avg,Y+ std,Y+ count,Y- avg,Y- std,Y- count,Y angle\n')
#for line in inFile:
if 1==1:
line = [1,2,38.702,37.867,35.821, 44, 49,55,65,20,25,28,89.]
line0= len(line)
print "the list size"
print line0
line1 = len(line) -5 #takes the overall line and subtracts 5.
print "the is the start of the 5 #'s we need"
print line1 #prints the line
d= line[line1:line0] #pops all the values from in the line (..)
print "these are the 5 #'s we need"
print d
lo=min(d)
hi=max(d)
print "the lowest value is"
print lo
print "the highest value is"
print hi
average1 = float (sum(d))/ len(d) #sum
print "the average of the values is"
print average1
“line = [1,2,38.702,37.867,35.821,44,49,55,65,20,25,28,89。]”部分我希望python自动读入coloumn,存储5最后的价值并进行上述数学分析。
答案 0 :(得分:1)
您可能想要使用像openpyxl这样的库,这里是关于如何访问某些单元格的文档示例。
columnOffset = 2 # column offset is (the letter as a number - 1), a = (1-1), b = (2-1)
rowOffset = 35 # row offset is row number - 1
wb = load_workbook('test.xlsx')
ws = wb.get_active_sheet()
for column in ws.columns[columnOffset:27]: #because you have 27 columns to parse through
for rowIndex, cell in enumerate(column[-5:]):
if rowIndex >= rowOffset:
print cell.value
不幸的是,openpyxl对列没有很好的支持,所以你必须使用索引来获取列。
基于xlrd
import xlrd
wb = xlrd.open_workbook("C:\Users\Asus\Desktop\herp.xls")
sh = wb.sheet_by_name(u'A Snazzy Title')
for index in xrange(2, 4):
lastFive = sh.col_values(index, start_rowx=59, end_rowx=64)
print lastFive
看起来xlrd将整个电子表格视为2D列表,所以请记住在0处开始索引。是的xlrd完全基于python。
归功于alexis,指出了这个模块。
答案 1 :(得分:0)
仅供参考,python-excel项目(http://www.python-excel.org/)中还有xlrd
/ xlwt
。不过,您还需要下载它。我从来没有使用openpyxl所以我不能说哪一个更好。