用于处理Excel工作表的Python脚本

我正在尝试编写一个Python脚本来操作Excel电子表格。

假设我有样本数据:

Gene chrom strand TSS TES Name NM_145215 chr5 + 135485168 135488045 Abhd11 NM_1190437 chr5 + 135485021 135488045 Abhd11 NM_1205181 chr14 + 54873803 54888844 Abhd4 NM_134076 chr14 + 54878906 54888844 Abhd4 NM_9594 chr2 + 31615464 31659747 Abl1 NM_1112703 chr2 + 31544075 31659747 Abl1 NM_207624 chr11 + 105829258 105851278 Abl1 NM_9598 chr11 + 105836521 105851278 Ace2 NM_1130513 chrX + 160577273 160626350 Ace2 NM_27286 chrX + 160578411 160626350 Ace2 

对于那些相似的名字(第6列),我想用最小的TSS检索整行。 例如,对于前2行-Abhd11名称,我想在自TSS 135485021 <135485168以来的结果中保存第二行。因此对于所有具有相同名称的集合。

任何想法和意见表示赞赏。

input

如果可能,我会将excel文件保存为csv文件,然后使用csv模块加载到python中。

或者,您可以使用xlrd模块读取excel文件 – 虽然我没有使用过这个,也不太了解它。

openpyxl是parsingexcel文件的附加选项(干杯只是另一个dunce)。

操纵

埃尔尼的想法似乎是可行的,我会执行如下。 假设linesreadfromfile是使用csv.reader读取的列表列表,即每个列表元素是与文件中该行的分隔条目对应的值的列表,

 finaldict = {} for row in linesreadfromfile: if finaldict.has_key(row[5]): if finaldict[row[5]][3] > row[3]: finaldict[row[5]] = row else: finaldict[row[5]] = row 

我同意mutzmatron,并会推荐xlrd模块。 这是一个简单的例子:

 import xlrd # Create your file handle file_handle = xlrd.open_workbook(file_name) # Use the first page in the spreadsheet (0-based indexes) sheet = file_handle.sheet_by_index(0) # Create dictionary for storing values abc = {} # Loop through every row for i in range(sheet.nrows): line = sheet.row_values(i) # Get your 'Name' and 'TSS' columns name = line[5] tss = line[3] # Add this 'Name' to your dictionary if it's new, or keep the max value if name not in abc.keys(): abc[name] = tss else: abc[name] = max(abc[name],tss) 

显然,根据你的规格改变你需要保存的内容(全行,某些值等)。

—编辑—

  # If this 'Name' is new, save this line if name not in abc.keys(): abc[name] = {'tss': tss, 'line': line} # Else, if this 'Name' is not new and the TSS is less, keep this new line elif tss < abc[name]['tss']: abc[name]['line'] = line 

你可以使用IronSpread ,它提供了一个python控制台,以及一种在python中编写脚本动作的方法。 它也支持可以用作普通的excel函数的UDF,这很好。

您可以使用Python工具for Visual Studio团队提供的Pyvot。 它为使用CPython的Excel电子表格提供了一个全面的API。

您可以从PyPi获取代码: http ://pypi.python.org/pypi/Pyvot您可以从Pytools网站获取文档: http ://pytools.codeplex.com/wikipage?title=Pyvot