将excel中的信息提取到python 2d数组中

我有一个Excel表格,date,时间和温度如下所示:

在这里输入图像说明

使用Python,我想提取这个信息到Python数组。

数组将获得位置0的date,然后将临时数据存储在以下位置,如下所示:

temparray[0] = [20130102,34.75,34.66,34.6,34.6,....,34.86] temparray[1] = [20130103,34.65,34.65,34.73,34.81,....,34.64] 

这是我的尝试,但它很糟糕:

 from xlrd import * print open_workbook('temp.xlsx') wb = open_workbook('temp.xlsx') for s in wb.sheets(): for row in range(s.nrows): values = [] for col in range(s.ncols): values.append(s.cell(row,col).value) print(values[0]) print("%.2f" % values[1]) print''' 

我用xlrd,但是我可以使用任何东西。 感谢您的帮助。

从我所了解的你的问题来看,问题是你希望输出是一个列表清单,而你没有得到这样的事情。

那是因为你的代码中没有任何东西甚至试图得到这样的东西。 对于每一行,build立一个列表,打印出列表的第一个值,打印出列表的第二个值,然后忘记列表。

要将每个行列表追加到列表的大列表中,您只需要将每个列值追加到行列表中就可以完成相同的操作:

 temparray = [] for row in range(s.nrows): values = [] for col in range(s.ncols): values.append(s.cell(row,col).value) temparray.append(values) 

从你的评论看来,你实际上想要的不仅仅是这个,而且也是每天将温度分组在一起,并且每天只添加第二列,而不是所有的值。 这不是你在问题中所描述的。 在这种情况下,你不应该循环遍历列。 你想要的是这样的:

 days = [] current_day, current_date = [], None for row in range(s.nrows): date = s.cell(row, 0) if date != current_date: current_day, current_date = [], date days.append(current_day) current_day.append(s.cell(row, 2)) 

这段代码假设date总是按sorting顺序排列,因为它们在input屏幕截图中。

我可能会以不同的方式构build,build立一个行迭代器传递给itertools.groupby ,但我希望保持这个新手友好,尽可能接近你原来的代码。

另外,我怀疑你真的不想要这个:

 [[date1, temp1a, temp1b, temp1c], [date2, temp2a, temp2b]] 

…而是像这样的东西:

 {date1: [temp1a, temp1b, temp1c], date2: [temp1a, temp1b, temp1c]} 

但不知道你打算怎么处理这个信息,我不能告诉你如何最好的存储它。

如果你想保留所有的date相同的数据,我可能会build议使用字典来获取特定date的临时列表。 然后,一旦你得到了与你的数据初始化字典,你可以重新安排你喜欢的方式。 在wb=open_workbook('temp.xlsx')之后尝试这样的事情:

 tmpDict = {} for s in wb.sheets(): for row in xrange(s.nrows): try: tmpDict[s.cell(row, 0)].append(s.cell(row, 2).value) except KeyError: tmpDict[s.cell(row, 0)] = [s.cell(row,2).value] 

如果你打印tmpDict,你应该得到如下的输出:

 {date1: [temp1, temp2, temp3, ...], date2: [temp1, temp2, temp3, ...] ...} 

字典密钥是以任意顺序保存的(它与密钥的哈希值有关),但是可以根据字典的内容构build一个列表列表,如下所示:

 tmpList = [] for key in sorted(tmpDict.keys): valList = [key] valList.extend(tmpDict[key]) tmpList.append(valList) 

然后,您将获得按datesorting的列表,就像您最初的工作一样。 但是,您始终可以使用键获取字典中的值。 我通常发现后来使用数据更容易,但是您可以将其更改为您需要的任何forms。