如何在Python脚本中生成仅整数随机数并导出Excel?
解决Python生成随机整数并保存到Excel的问题
嘿,这问题很容易搞定!你现在只需要把生成浮点数的随机函数换成生成整数的就行,我给你两种常用的方案,结合你的代码来改:
方案1:用Python内置的random库生成整数
如果你习惯用random模块,把原来生成浮点数的代码(比如random.random())换成random.randint(min_val, max_val)就行,这个函数会生成包含min和max在内的整数。
比如你的代码可以改成这样:
import numpy as np import openpyxl import random from openpyxl import Workbook # Create workbook object wb = openpyxl.Workbook() sheet = wb.active # 新版本openpyxl推荐用wb.active替代get_active_sheet() sheet.title = 'Sheet #1' # Generate data # 假设你需要生成10个时间戳对应的数据 Timestamp = list(range(10)) # 0到9的整数时间戳 # 生成三个整数列表,这里我指定了范围,你可以自己调整 List1 = [random.randint(0, 50) for _ in range(len(Timestamp))] List2 = [random.randint(50, 100) for _ in range(len(Timestamp))] List3 = [random.randint(100, 150) for _ in range(len(Timestamp))] # 写入Excel表头 sheet.append(["Timestamp", "List1", "List2", "List3"]) # 逐行写入数据 for t, l1, l2, l3 in zip(Timestamp, List1, List2, List3): sheet.append([t, l1, l2, l3]) # 保存文件 wb.save("integer_random_data.xlsx")
方案2:用numpy生成整数数组
如果你更习惯用numpy,那可以用np.random.randint(low, high, size),注意这里的high是开区间(也就是生成的数不会包含high),所以如果要生成0到100的整数,需要写np.random.randint(0, 101, size=...)。
示例代码:
import numpy as np import openpyxl from openpyxl import Workbook # Create workbook object wb = openpyxl.Workbook() sheet = wb.active sheet.title = 'Sheet #1' # Generate data with numpy Timestamp = np.arange(10).tolist() # 用numpy生成0-9的整数转成列表 # 生成三个整数数组,转成列表 List1 = np.random.randint(0, 51, size=len(Timestamp)).tolist() List2 = np.random.randint(50, 101, size=len(Timestamp)).tolist() List3 = np.random.randint(100, 151, size=len(Timestamp)).tolist() # 写入Excel sheet.append(["Timestamp", "List1", "List2", "List3"]) for row in zip(Timestamp, List1, List2, List3): sheet.append(list(row)) wb.save("numpy_integer_data.xlsx")
关键注意点
random.randint(a, b):包含a和b两个端点值np.random.randint(low, high, size):不包含high,所以要生成到N的整数,high要写N+1- 新版本openpyxl中
get_active_sheet()已经被弃用,建议用wb.active获取当前活动工作表,避免运行警告
内容的提问来源于stack exchange,提问作者Giroud2
相关产品推荐
相关产品推荐

