zoukankan      html  css  js  c++  java
  • Python系列(5)——解决xlrd读取excel的.xls文件时读取出的数据默认是浮点型的问题

     1 # -*-coding:utf-8 -*-
     2 # 在使用xlrd读取excel的.xls类型文件时,读取的数据默认为浮点型,包括对整数型/时间/布尔值...类型数据的读取,
     3 # 因此在按行或列的方式读取sheet数据时进行数据类型转换
     4 import xlrd
     5 read_book = xlrd.open_workbook(r'C:UsersAdministratorDesktop	est.xls')  # 打开文件


    6 # 1.读取sheet对象 7 work_sheet_index = read_book.sheet_by_index(0) # 通过sheet索引获得sheet对象 8 # 2.获取指定sheet基本信息 9 sheet_name = work_sheet_index.name # 获取索引为0的sheet姓名 10 sheet_row = work_sheet_index.nrows # 获取该sheet的总行数 11 sheet_col = work_sheet_index.ncols # 获取该sheet的总列数 12 # 3.按行或列的方式获得sheet数据 13 for i in range(sheet_row): 14 print(work_sheet_index.row_values(i)) # 每一行的数据用一个列表表示,但读出的数据默认为浮点型 15
    
    16 # 以下代码是对用xlrd读取excel数据时默认是浮点型数据的转换代码
    17 import datetime
    18 import  numpy as np
    19 list_cell = []
    20 # ②dict_key = []
    21 for i in range(sheet_row):
    22     list_during = []
    23     # ①list_during = {}
    24     for j in range(sheet_col):
    25         cell_type = work_sheet_index.cell(i, j).ctype  # 表格的数据类型
    26         # 判断python读取的返回类型  0 --empty,1 --string, 2 --number(都是浮点), 3 --date, 4 --boolean, 5 --error
    27         cell = work_sheet_index.cell_value(i, j)   # 获取单元格的值
    28         if cell_type == 2 and cell % 1 == 0.0:
    29             cell = int(cell)   # 浮点转成整型
    30         elif cell_type == 3:
    31             date = datetime.datetime(*xlrd.xldate_as_tuple(cell, 0))   # 第一个参数是要处理的单元格,第二个参数是时间基准0代表以1900-01-01为基准
    32             cell = date.strftime('%Y/%m/%d')   # 转为字符串
    33         elif cell_type == 4:
    34             if cell == 1:
    35                 cell = True
    36             else:
    37                 cell = False
    38         """
    39         若想变成key对应value,即大列表里是字典且每个key列名都对应cell单元格值
    40         ①list_during={}变成空字典
    41         ②增加dict_key = []
    42         ③将i=0的第一行设为key值并增加相应的if条件
    43         ④最后将字典append列表中时也增加if条件,第一个字典即列名不单独作为一个元素放到列表中

    44 """ 45 # ③if i == 0: 46 # dict_key.append(cell) # 第一行为列名即为key 47 # else: 48 # list_during[dict_key[j]] = cell 49 list_during.append(cell) 50 # ④if i == 0: 51 # del list_during 52 # else: 53 # list_cell.append(list_during) 54 list_cell.append(list_during) 55 56 print(np.array(list_cell)) # 直接使用np.array()进行列表换行

  • 相关阅读:
    静态链接到 MFC 的规则 DLL
    DLLAFX_MANAGE_STATE(AfxGetStaticModuleState())模块状态切换保护
    多线程专题之线程同步(1)
    UVa 4256 Salesmen dp
    nefu 661 Clockwise 水DP+略几何
    10635 Prince and Princess LCS&LIS
    UVa 3882 And Then There Was One 递推无力orz
    UVa 10192 Vacation 字符串dp
    UVa 11584 Partitioning by Palindromes 回文串dp
    UVa 10534 Wavio Sequence LIS
  • 原文地址:https://www.cnblogs.com/www123yyy123/p/13355678.html
Copyright © 2011-2022 走看看