
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学习有所帮助。