正在读取excel文件,但只显示一行

2024-06-16 13:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用xlrd读取一个XLS文件

    import xlrd
    iedb = {} #Empty dictionary 
    book = xlrd.open_workbook('sampledata.xlsx')
    sh = book.sheet_by_index(0)
    for i in range(1,sh.nrows): #skips first line.
         iedb[sh.cell_value(rowx=i,colx=1)] = \
              sh.cell_value(rowx=i,colx=2)

我的excel文件是“sampledata.xlsx”

Reference   IEB ID  Epitope Name
I_N_Glaspole_Allergy_2005   221 Ara_h_2_(1-20)
I_N_Glaspole_Allergy_2005   920 Ara_h_2_(10-29)
I_N_Glaspole_Allergy_2005   921 Ara_h_2_(19-38)
I_N_Glaspole_Allergy_2005   922 Ara_h_2_(28-47)

因此,我得到所需的输出如下:

{221.0: 'Ara h 2 (1-20)', 920.0: 'Ara h 2 (10-29)', 921.0: 'Ara h 2 (19-38)', 922.0: 'Ara h 2 (28-47)'}

但在程序中,如果我将列号改为0和1,而不是1和2,即:

    iedb[sh.cell_value(rowx=i,colx=0)] = \
         sh.cell_value(rowx=i,colx=1)

我希望输出有4个条目,但它只给出一个条目,如下所示:

{'I N Glaspole Allergy 2005': 922.0}

请解释…我的版本是3.6.4


Tags: 文件valueshcell条目xlsxxlrdsampledata
1条回答
网友
1楼 · 发布于 2024-06-16 13:31:54

Reference列具有所有相同的值,dict键必须是唯一的,因此每个条目只是覆盖上一个条目

您有几个选项,使用list,例如:

iedb = []
...
for i in range(1,sh.nrows):
    iedb.append((sh.cell_value(rowx=i,colx=0), sh.cell_value(rowx=i,colx=1)))

或者将value中的dict作为结果列表:

iedb = {}
...
for i in range(1,sh.nrows):
    iedb.setdefault(sh.cell_value(rowx=i,colx=0), []).append( sh.cell_value(rowx=i,colx=1))

相关问题 更多 >