python根据excel的一列数据产生加权随机数

python根据excel的一列数据产生加权随机数

需求

最近遇到一个奇葩的事,行政那边说,让估算一下明年的这些杂七杂八费,然后给了我一个excel,里面有200多个这样的费用。我没做过行政,也搞不清这个到底咋来,为什么要弄这玩意。一番交流,原来是上头要的,不一定看,但是东西得有,让我弄个数字和去年差不多的就行。于是变有了下面的故事

设计

1.需要读取excel. 用的库是xlwing。可以根据sheet名称定位sheet,然后用range()方法定位一行,一列,或者指定几个单元格。
例如:定位 A1到A3 ,range1=sheet.range("A1:A3")
具体用法很多,在xlwing的官网上有介绍。http://docs.xlwings.org/en/stable/api.html
2.需要产生随机数,用的库是numpy,产生一个加权的随机数,然后我用的加权随机数规则为:
【-10%,概率10%】【不变,概率30%】【+2%,概率30%】【+5%,概率20%】【+10%,概率10%】

代码实现

代码中分为两个function,一个是读取excel,一个是根据一个值,产生一个加权随机数。观众老爷可以参考,对有疑问的地方,可以再来与我沟通O(∩_∩)O

# -*- coding: UTF-8 -*-
import xlwings
import numpy as np
def import_excel(filename, sheet_name, source,target):
    '''
    导入一个excel,根据某一列的值,产生一个加权随机数,覆盖掉另一列的值
    :param filename: excel路径
    :param sheet_name: sheet的名字
    :param source: 源列的第一个值 如:A1,C1
    :param target: 目标列的第一个值,如B1,D2
    :return:
    '''
    app = xlwings.App(visible=False, add_book=True)
    app.display_alerts = False
    app.screen_updating = False
    wb = app.books.open(filename)
    sht = wb.sheets[sheet_name]
    rng1 = sht.range(source)
    rng2 = sht.range(source).end('down')
    rng3 = sht.range(rng1, rng2)
    all_rng = rng3.value
    list_dest = []
    for item in all_rng:
        dest_item = arithmetic(item)
        # 这里要把结果变成[[1],[2]]这样的形式,才是一列的数据
        # 如果是[1,2]这样,是一行的数据
        list_temp = []
        list_temp.append(dest_item)
        list_dest.append(list_temp)
    sht.range(target).value = list_dest
    wb.save(filename)
    wb.close()
    app.quit()
def arithmetic(source):
    '''
    加权随机算法
    :param source: 输入一个原值
    :return: 返回浮动后的值
    '''
    power = np.array([0.1, 0.3, 0.3, 0.2, 0.1])
    index = np.random.choice([-0.1, 0, 2, 5, 10], p=power.ravel())
    rand = source * index / 100
    dest = int(source + rand)
    return dest
if __name__ == '__main__':
    import_excel("Book1.xlsx", 'Sheet1','C2','D2')

运行结果


苏ICP备18047533号-2