Python实现Excel随机抽取数

有这样一组数据:

Python实现Excel随机抽取数_第1张图片

现在要随机抽取十个数字,代码如下:

import sys
import xlrd
import random

print("pm2.5   天津")
#打开Excel
workbook = xlrd.open_workbook('2.xls')

#进入sheet
excel_sheet = workbook.sheet_by_index(0)

#获取行数和列叔
nrows_num = excel_sheet.nrows
ncols_num = excel_sheet.ncols
i=1
while i<=10:
    if nrows_num > 10:
    #生成随机数
        random_num = random.randint(1,nrows_num-1)
        number = excel_sheet.row(random_num)[1].value
        name = excel_sheet.row(random_num)[2].value
        print(number,name)
      # print(name)
        i = i + 1
    else:
        print("数据不足,请添加")
        break
运行:

pm2.5   天津
35.92 0.3129
79.1866 0.253475
121.7066 0.125175
91.6 0.541348
121.7066 0.125175
162.2133 0.917009
21.56 0.0599271
130.4666 0.338327
58.7733 0.382621
66.8666 0.703601

即可实现。




你可能感兴趣的:(杂七杂八)