excel表格是我們處理數據的工具,在python編程中,也有對excel表格的操作。本文主要向大家介紹python中讀取excel某列數據的代碼,并演示將讀取的數據變為浮點數的過程。
一、python讀取excel某列數據
importxlrd
worksheet=xlrd.open_workbook('E:\\Crawl\\000002.xls')
sheet_names=worksheet.sheet_names()
print(sheet_names)
forsheet_nameinsheet_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]))#查看數據類型
輸出結果為
['Sheet1']
['','','-72.20','248.84','-32.67','156.93','-49.58','59.36','']
248.84
二、將讀取的數據變為浮點數
importxlrd
worksheet=xlrd.open_workbook('E:\\Crawl\\000002.xls')
sheet_names=worksheet.sheet_names()
print(sheet_names)
forsheet_nameinsheet_names:
sheet=worksheet.sheet_by_name(sheet_name)
rows=sheet.nrows#獲取行數
cols=sheet.ncols#獲取列數,盡管沒用到
all_content=[]
foriinrange(rows):
cell=sheet.cell_value(i,3)#取第二列數據
try:
cell=float(cell)#轉換為浮點數
all_content.append(cell)
exceptValueError:
pass
print(all_content)
print(all_content[3])
print(type(all_content[3]))
以上內容為大家介紹了python中如何讀取excel某列數據?希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。