简体   繁体   English

使用xlrd读取python中的选定列和所有行

[英]Using xlrd to read selected columns and all rows in python

I would like to loop through an excel table and get the values for selected columns in each row in a set of lists or dictionary. 我想遍历一个excel表并获取一组列表或字典中每一行中选定列的值。 if in a dictionary, for each row, the value in the first selected column would be the key and the values in the other selected columns would be the values (array) for that key. 如果在字典中,则对于每一行,第一个选定列中的值将是键,而其他选定列中的值将是该键的值(数组)。 I cannot figure out how to tell python to read values from only selected columns...for the excel table may have 10 columns but I am only interest in three for example, and the three of interest are not contiguous. 我无法弄清楚如何告诉python只从选定的列中读取值...因为excel表可能有10列,但是例如,我只对三列感兴趣,而感兴趣的三列并不连续。 Would appreciate your insights using XLRD. 感谢您使用XLRD的见解。

    import xlrd
    from xlrd import open_workbook
    import arcpy

    wb = open_workbook ("c:\\Users\\Admin\\Documents\\Marion\\Courses\\GEOG485\\FinalProject\\Data\\ExcelFiles\\Belize_Culvert_Nov15_V4.0.xlsx")

    sheet = wb.sheet_by_index(1)

    keys = [sheet.cell(0, 5).value for col_index in xrange(sheet.ncols)]

    dict_list = []
    for rownum in range(sheet.nrows):
        d = {keys[col_index]: sheet.cell(0, 5).value 
        for col_index in xrange(sheet.ncols)}:
            dict_list.append(d)

The field that I want to use as key is column 5 and the values are columns #16 and #17 as an array value for each key... 我想用作键的字段是第5列,值是第16列和第17列,作为每个键的数组值...

Use this command 使用此命令

row_slice(rowx, start_colx=0, end_colx=None)

Returns a slice of the Cell objects in the given row. 返回给定行中的Cell对象的一部分。

Some issues in your code - 您的代码中的一些问题-

  1. keys = [sheet.cell(0, 5).value for col_index in xrange(sheet.ncols)] - This always takes the keys as the value in the first row and 6th column (Rows and columns are 0 indexed.) keys = [sheet.cell(0, 5).value for col_index in xrange(sheet.ncols)]的值keys = [sheet.cell(0, 5).value for col_index in xrange(sheet.ncols)] -这始终将键作为第一行和第六列中的值(行和列的索引为0。)

  2. d = {keys[col_index]: sheet.cell(0, 5).value - This is not even valid python syntax d = {keys[col_index]: sheet.cell(0, 5).value这甚至不是有效的python语法

You can just loop over all the rows, take column index 4 (5th column) as key and the rest in a list and add that to a dictionary, Example - 您可以遍历所有行,将列索引4(第5列)作为键,将其余的索引添加到列表中,然后将其添加到字典中,例如-

import xlrd
from xlrd import open_workbook
import arcpy

wb = open_workbook ("c:\\Users\\Admin\\Documents\\Marion\\Courses\\GEOG485\\FinalProject\\Data\\ExcelFiles\\Belize_Culvert_Nov15_V4.0.xlsx")

sheet = wb.sheet_by_index(1)
sheetdict = {}
for rownum in range(sheet.nrows):
    sheetdict[sheet.cell(rownum,4)] = [sheet.cell(rownum,15),sheet.cell(rownum,16)]

In the end, sheetdict has the required dictionary. 最后, sheetdict具有必需的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM