MENU

帕累托累积分布

前两天实验室师妹来问平时我们计算腹地的前百分之多少的人怎么定这个到底怎么计算,以及每次都要数据库到处数据excel算这个问题,想想自己也需要tableau连接数据库做可视化后挑选出相应的分段值,就想着写个脚本来实现。花了半个小时写了个直接读取csv输出最靠近10,20....90%分段值的数,查了下还是没搞明白是不是叫帕累托累积分布,不过应该是一种累积分布。

后续需要修改的就是让python直接读取postgresql数据库,然后在排序计算分段值,而且要提高下效率,现在的计算效率不是很高,不过现在能用就行(此处要配个罗玉龙那个又不是不能用的牌子233)。

顺便学了下github,把代码也放了上去,以后代码也都放github上。

https://github.com/imcake/pareto


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-11-01
# @Author  : imcake (likaike@gmail.com)
# @Link    : https://github.com/imcake

##############################################
# 计算累积频率分段值(帕累托图)
# 输入带有需要累积的值的csv文件和该值的字段名
# 输出百分之10-90对应的最相近数值
# 输出结果为字典,10:xxx, 20:xxx, ..., 90:xxx
#############################################
import pandas as pd


def get_pareto_penct(csv_name, value_column):
    data_df = pd.read_csv(csv_name, header=0)
    pencentList = []
    pencentage = 0
    for i in range(len(data_df)):
        rawList = data_df[value_column].tolist() # change colume to list
        rawList.sort(reverse=True)
        pencent = float(rawList[i]) / sum(rawList) * 100
        pencentage = pencentage + pencent # calculate the accumulated pencentage
        pencentList.append(pencentage)
    # add pencentage and raw date to a dict
    dictionary = dict(zip(pencentList, rawList))
    init_penct = [10, 20, 30, 40, 50, 60, 70, 80, 90]
    value = []
    for j in init_penct:
        # get the closest raw date of certain pencentage
        dict_key = min(pencentList, key=lambda x: abs(x - j))
        value.append(dictionary.get(dict_key))
    result_dict = dict(zip(init_penct, value))
    return result_dict


if __name__ == '__main__':
    csv_name = 'pareto.csv' # csv文件名
    value_column = 'TOTAL' # 需要累积的字段名
    print get_pareto_penct(csv_name, value_column)

Tags: coding, PhD, python
Archives QR Code
QR Code for this page
Tipping QR Code
Leave a Comment

bst g22 jinniu lilai opebet orange88 vinbet xbet yuebo zunlong shijiebei bet007 hg0088 ju111 letiantang m88 mayaba qg777 qianyiguoji sbf777 tengbohui tlc ule weilianxier waiweitouzhu xingfayule xinhaotiandi yinheyule youfayule zhongying 2018shijiebei w88 18luck 188bet beplay manbet 12bet 95zz shenbo weide1946 ca88 88bifa aomenxinpujing betway bodog bt365 bwin tongbao vwin weinisiren 88jt fenghuangyule hongyunguoji 918botiantang huanyayule jianada28 jixiangfang libo long8 hongzuyishi zuqiutouzhu