【问题标题】:How to change the starting index and have it read only to a specific row not the entire rows?如何更改起始索引并使其仅读取特定行而不是整行?
【发布时间】:2019-08-30 14:07:22
【问题描述】:

我想编写一个循环来遍历 excel 文件中的一行,但我想从某个索引行开始并在某个行结束,而不是遍历整个内容。我是 python 新手,不知道它的确切语法谢谢。

我尝试查找 n.rows 函数以查看是否有任何可以设置的限制,但我找不到任何限制。

  book = 
  xlrd.open_workbook("/Users/vhim/Documents/Cases/Orders.xlsx")
  sheet = book.sheet_by_name("Summary")
  #print(sheet.col_values(1))

  i = 0
  #for col in range (sheet.ncols):
  for row in range (sheet.nrows):
        i = i+1
        print(sheet.col_values(i))

【问题讨论】:

    标签: python excel dataframe data-analysis


    【解决方案1】:

    您可以尝试使用 Pandas 库,您可以读取 excel 文件跳过第一行,也可以跳过最后一行,例如:

    import pandas as pd
    xls = pd.ExcelFile("/Users/vhim/Documents/Cases/Orders.xlsx")
    page_summary = pd.read_excel(xls, "Summary", skiprows = 100, nrows = 200)
    

    这将从第 100 行读取到第 300 行,现在进行迭代:

    for row in page_summary.iterrows:
         print(row[1]['COLUMN NAME'])
    

    【讨论】:

      【解决方案2】:

      range 可以在您想要的任何地方启动和停止。使用sheet.row 获取特定工作表

      book = xlrd.open_workbook("temp.xlsx")
      sheet = book.sheet_by_name("Summary")
      
      # rows 3, 4, 5, and 6
      first, last = 3,6
      for rowx in range(first, last+1):
          rowx_cells = sheet.row(rowx)
      

      【讨论】:

      • 如何对列中的多个特定行执行此操作
      • @VathanaHim:使用cels = sheet.col(colx) 获取列中的单元格序列,然后将序列切片为您想要的行values = cels[first:last+1] 有很多方法可以利用@987654323 @ - sheet.col_slice() 会起作用。
      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多