• 技术文章 >常见问题 >Python常见问题

    python中如何读取excel某列数据?

    宋雪维宋雪维2020-12-21 17:28:32原创7096

    excel表格是我们处理数据的工具,在python编程中,也有对excel表格的操作。本文主要向大家介绍python中读取excel某列数据的代码,并演示将读取的数据变为浮点数的过程。

    一、python读取excel某列数据

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    import xlrd

    worksheet = xlrd.open_workbook('E:\\Crawl\\000002.xls')

    sheet_names= worksheet.sheet_names()

    print(sheet_names)

    for sheet_name in sheet_names:

        sheet = worksheet.sheet_by_name(sheet_name)

        rows = sheet.nrows # 获取行数

        cols = sheet.ncols # 获取列数,尽管没用到

        all_content = []

     

        cols = sheet.col_values(3) # 获取第二列内容, 数据格式为此数据的原有格式(原:字符串,读取:字符串;  原:浮点数, 读取:浮点数)

        print(cols)

        print(cols[3])

        print(type(cols[3]))    #查看数据类型

    输出结果为

    1

    2

    3

    4

    5

    6

    7

    ['Sheet1']

     

    ['', '', '-72.20', '248.84', '-32.67', '156.93', '-49.58', '59.36', '']

     

    248.84

     

    <class 'str'>

    二、将读取的数据变为浮点数

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    import xlrd

    worksheet = xlrd.open_workbook('E:\\Crawl\\000002.xls')

    sheet_names= worksheet.sheet_names()

    print(sheet_names)

    for sheet_name in sheet_names:

        sheet = worksheet.sheet_by_name(sheet_name)

        rows = sheet.nrows # 获取行数

        cols = sheet.ncols # 获取列数,尽管没用到

        all_content = []

        for i in range(rows) :

            cell = sheet.cell_value(i, 3) # 取第二列数据

            try:

                cell = float(cell) # 转换为浮点数

                all_content.append(cell)

            except ValueError:

                pass

        print(all_content)

        print(all_content[3])

        print(type(all_content[3]))

    以上就是python中读取excel某列数据的代码,以及演示将读取的数据变为浮点数的过程。大家可以直接套用使用哦~希望能对你的python学习有所帮助。

    专题推荐:pythonexcel数据
    上一篇:python中remove与del的区别是什么? 下一篇:如何使用Python脚本完成视频播放?

    相关文章推荐

    • python bottle框架怎么用?• python中reshape函数怎么用?• python concat函数有何用法?• python中softmax函数如何用?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网