我是Python的新手。基本上,我想编写一个程序来读取excel文件中的列D
和E
,并计算总的Incoming
和Outgoing
持续时间。
哪个Python模块用于读取excel文件以及如何处理其中的数据?
Excel文件:
D E
Incoming 18
Outgoing 99
Incoming 20
Outgoing 59
Incoming 30
Incoming 40
根据您使用的excel版本,有几个选项。 openpyxl - 用于读取Excel 2010文件(即:.xlsx) xlrd - 用于读取旧的Excel文件(即:.xls)
我只使用了xlrd,你可以做类似下面的事情 **注意**代码未经测试
import xlrd
current_row = 0
sheet_num = 1
input_total = 0
output_total = 0
# path to the file you want to extract data from
src = r'c:\temp\excel sheet.xls'
book = xlrd.open_workbook(src)
# select the sheet that the data resids in
work_sheet = book.sheet_by_index(sheet_num)
# get the total number of rows
num_rows = work_sheet.nrows - 1
while current_row < num_rows:
row_header = work_sheet.cell_value(current_row, 4)
if row_header == 'output':
output_total += work_sheet.cell_value(current_row, 5)
elif row_header == 'input':
input_total += work_sheet.cell_value(current_row, 5)
print output_total
print input_total
看起来简单地使用Excel的=SUMIF()
函数就足够了。但是,你需要一个Python解决方案,所以这是一个Python解决方案!
Pandas是一个提供与Excel电子表格非常相似的DataFrame数据结构的库。它提供了read_excel()
函数,其文档可以找到here。拥有DataFrame后,您可以执行以下操作:
import pandas as pd
table = pd.read_excel('path-to-spreadsheet.xlsx')
incoming_sum = table.E[table.D == 'Incoming'].sum()
outgoing_sum = table.E[table.D == 'Outgoing'].sum()
你可以在Windows上获得Pandas for Python,但这有点困难。最简单的方法是Windows的Scientific Python发行版,如Anaconda。在Linux上,安装pandas
很简单,就像sudo pip install pandas
一样。
在Python 3.4.1中使用xlrd 0.9.3:
它将行D
和E
中的所有值放在两个单独的list
中。
然后它使用zip()
将这些列表的每个并行元素(只是具有相同索引的元素)组合到元组。
然后,将这些生成的元组组合成一个list
。使用sum()
和列表理解,计算incoming_sum
和outgoing_sum
。
import xlrd
with xlrd.open_workbook('z.xlsx') as book:
# 0 corresponds for 1st worksheet, usually named 'Book1'
sheet = book.sheet_by_index(0)
# gets col D values
D = [ D for D in sheet.col_values(3) ]
# gets col E values
E = [ E for E in sheet.col_values(4) ]
# combines D and E elements to tuples, combines tuples to list
# ex. [ ('Incoming', 18), ('Outgoing', 99), ... ]
data = list( zip(D, E) )
# gets sum
incoming_sum = sum( tup[1] for tup in data if tup[0] == 'Incoming' )
outgoing_sum = sum( tup[1] for tup in data if tup[0] == 'Outgoing' )
print('Total incoming:', incoming_sum)
print('Total outgoing:', outgoing_sum)
输出:
Total incoming: 108.0
Total outgoing: 158.0
要安装xlrd :( Windows)
cmd
的当前目录(chdir
)更改为您解压缩的目录,然后键入cmd python setup.py install
请注意,您将提取xlrd-0.9.3.tar.gz
两次,首先删除.gz
,第二次删除.tar
。
提取的目录(您将更改cmd的当前目录)将如下所示: