Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用xlrd在python中按列名读取Excel数据_Python_Excel_Python 3.x_Xlrd - Fatal编程技术网

如何使用xlrd在python中按列名读取Excel数据

如何使用xlrd在python中按列名读取Excel数据,python,excel,python-3.x,xlrd,Python,Excel,Python 3.x,Xlrd,我正在尝试读取大型excel文件(近100000行)的数据。 我使用python中的“xlrd模块”从excel中获取数据。 我想按列名(Cascade,Schedule name,Market)而不是列号(0,1,2)获取数据。 因为我的excel列不是固定的。 我知道在固定列的情况下如何获取数据 下面是我从excel for fixed列中获取数据的代码 import xlrd file_location =r"C:\Users\Desktop\Vision.xlsx" workbook

我正在尝试读取大型excel文件(近100000行)的数据。 我使用python中的“xlrd模块”从excel中获取数据。 我想按列名(Cascade,Schedule name,Market)而不是列号(0,1,2)获取数据。 因为我的excel列不是固定的。 我知道在固定列的情况下如何获取数据

下面是我从excel for fixed列中获取数据的代码

import xlrd

file_location =r"C:\Users\Desktop\Vision.xlsx"
workbook=xlrd.open_workbook(file_location)
sheet= workbook.sheet_by_index(0)
print(sheet.ncols,sheet.nrows,sheet.name,sheet.number)

for i in range(sheet.nrows):
   flag = 0
   for j in range(sheet.ncols):
      value=sheet.cell(i,j).value
如果有人对此有任何解决办法,请告诉我

谢谢

注释:当
fieldnames=['Cascade','Market','Schedule','Name]

表(['Cascade','Schedule','Name','Market'])
是相等的

col_idx
中保持
字段名的顺序并不是我最初的目标


问题:我想按列名获取数据

以下
OOP
解决方案将起作用:

class OrderedByName():
    """
    Privides a generator method, to iterate in Column Name ordered sequence
    Provides subscription, to get columns index by name. using class[name]
    """
    def __init__(self, sheet, fieldnames, row=0):
        """
        Create a OrderedDict {name:index} from 'fieldnames'
        :param sheet: The Worksheet to use
        :param fieldnames: Ordered List of Column Names
        :param row: Default Row Index for the Header Row
        """
        from collections import OrderedDict
        self.columns = OrderedDict().fromkeys(fieldnames, None)
        for n in range(sheet.ncols):
            self.columns[sheet.cell(row, n).value] = n

    @property
    def ncols(self):
        """
        Generator, equal usage as range(xlrd.ncols), 
          to iterate columns in ordered sequence
        :return: yield Column index
        """
        for idx in self.columns.values():
            yield idx

    def __getitem__(self, item):
        """
        Make class object subscriptable
        :param item: Column Name
        :return: Columns index
        """
        return self.columns[item]
用法

输出

cell((0, 1)).value == Cascade
cell((0, 2)).value == Market
cell((0, 0)).value == Schedule
cell((1, 1)).value == DO Macro Upgrade
cell((1, 2)).value == Upper Cnetral Valley
cell((1, 0)).value == SF05UB0
cell((2, 1)).value == DO Macro Upgrade
cell((2, 2)).value == Toledo
cell((2, 0)).value == DE03HO0
cell((3, 1)).value == DO Macro Upgrade
cell((3, 2)).value == SF Bay
cell((3, 0)).value == SF73XC4

按名称获取一列的索引

print("cell{}.value == {}".format((1, by_name['Schedule']),
                                    sheet.cell(1, by_name['Schedule']).value))
#>>> cell(1, 0).value == SF05UB0

使用Python:3.5测试

或者您也可以使用,它是一个内置的综合数据分析库

其中,快速查看生成的数据帧
df
将显示:

In [1]: df
Out[1]:
   Cascade     Schedule Name                Market
0  SF05UB0  DO Macro Upgrade  Upper Central Valley
1  DE03HO0  DO Macro Upgrade                Toledo
2  SF73XC4  DO Macro Upgrade                SF Bay

您的列名在电子表格的第一行,对吗?因此,阅读第一行并构造从名称到列索引的映射

column_pos = [ (sheet.cell(0, i).value, i) for i in range(sheet.ncols) ]
colidx = dict(column_pos)
或作为一个班轮:

colidx = dict( (sheet.cell(0, i).value, i) for i in range(sheet.ncols) )
然后可以使用索引来解释列名,例如:

print(sheet.cell(5, colidx["Schedule Name"]).value)
要获得整个列,可以使用列表:

schedule = [ sheet.cell(i, colidx["Schedule Name"]).value for i in range(1, sheet.nrows) ]

如果确实需要,可以为处理解释的
单元格
函数创建一个包装器。但我认为这很简单。

你可以利用熊猫。下面是用于标识excel工作表中的列和行的示例代码

import pandas as pd

file_location =r"Your_Excel_Path"

# Read out first sheet of excel file and return as pandas dataframe
df = pd.read_excel(file_location)


total_rows=len(df.axes[0])
total_cols=len(df.axes[1])

# Print total number of rows in an excel sheet
print("Number of Rows: "+str(total_rows))

# Print total number of columns in an excel sheet
print("Number of Columns: "+str(total_cols))

# Print column names in an excel sheet
print(df.columns.ravel())

现在,一旦您有了列数据,就可以将其转换为值列表。

您的问题,并给出“按列名称而不是列编号”的示例。我已在问题中进行了更改。您能告诉我如何进行更改吗?谢谢Alexis的回答。我想获取“schedule name”的完整数据,而不是单个值。你能告诉我怎么做吗?好的。(我假设第0行包含列名,因此它不包含在列值中。)感谢stovfl的回答,但您只在中打印列索引,但我想打印列名对应的所有数据。您能告诉我如何使用这些列索引来获取it@George.S:根据您的问题:“我知道在固定列的情况下如何获取数据。”。您可以询问并显示一个非固定数据表,以及如何使用
col\u idx
列表执行此操作。实际上,“我知道如何在固定列的情况下获取数据。”但问题是,如果我更改excel的列标题,您的代码中会出现问题。它可以按相同的顺序打印列索引。那么,告诉我,我的代码如何知道哪个标头位于哪个列中。我想我已经澄清了我的观点。感谢您的更新,但当字段名['Cascade'、'Market'、'Schedule'、'Name]和工作表(['Cascade'、'Schedule'、'Name'、'Market'])的标题相等时,它仍然不起作用。它没有显示列标题的确切位置。感谢Xukrao的回答,但我不知道如何使用pandas对excel数据执行操作。所以我无法使用它。正如op对@Xukrao的答案所评论的那样,它也使用熊猫,op不知道如何使用熊猫。
schedule = [ sheet.cell(i, colidx["Schedule Name"]).value for i in range(1, sheet.nrows) ]
import pandas as pd

file_location =r"Your_Excel_Path"

# Read out first sheet of excel file and return as pandas dataframe
df = pd.read_excel(file_location)


total_rows=len(df.axes[0])
total_cols=len(df.axes[1])

# Print total number of rows in an excel sheet
print("Number of Rows: "+str(total_rows))

# Print total number of columns in an excel sheet
print("Number of Columns: "+str(total_cols))

# Print column names in an excel sheet
print(df.columns.ravel())