项目07_社会财富分配问题模拟

‘‘‘

-- coding: utf-8 --

Created on Fri Oct 12 12:31:21 2018

项目 13 社会财富分配问题 (蒙特卡罗模拟)
Note:
1 建立一个空的DataFrame时,只需要index 参数
2 当在一个列表中随机选取一个值 可以用random的choice,当需要随机选取多个值用numpy
的random的choice()
3 Series 的name 参数设置在Series 中 name=‘’
4 当在DataFrame需要判断再赋值时,可以先用判断筛选列 重新赋值 或者 用apply函数
5 apply在DataFrame中用于判断赋值(☆)
6 在绘制图表时 如果不想显示每一个xticks 不要xlim的?
7 在迭代过程中不要将值赋值给变量名和传入的变量一致,会导致报错
8 在筛选时或者标记 当对某些值进行筛选或者按某些条件筛选 即按照此标记
"""

导入模块

import os
import random
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings('ignore')

定义函数

def round1():
'''
建立初始模型,第1次交易
'''
# 构建初始财富值100,index的值为每个人的编号
people = pd.DataFrame(index=list(range(1,101)))
people['money'] = 100
people['r1'] = people['money'] - 1

# 构建收钱的随机对象
people['to'] = np.random.choice(list(range(1,101)), size=100,
      replace=True, p=None)
data_to = people['to'].value_counts()
data_to.name = 'count'
data_to = pd.DataFrame(data_to)
people = pd.merge(people, data_to, how='left', left_index=True,
                  right_index=True).fillna(0)
people['r1_m'] = people['r1'] + people['count']

return people    

def roundi(n):
'''
构建借贷模型
不考虑财富值为0,即允许借贷
'''
# 构建初始财富值
people = pd.DataFrame(index=list(range(1,101)))
people['r0'] = 100

# 构建模型
for i in range(1, n+1): 
    col = 'r' + str(i)
    col0 = 'r' + str(i-1)
    people[col] =  people[col0] - 1
    data_to = pd.Series(np.random.choice(list(range(1,101)), size=100,
      replace=True, p=None), name='to')
    data_to = data_to.value_counts()
    data_to = pd.DataFrame(data_to)
    people = pd.merge(people, data_to, how='left', left_index=True,
                  right_index=True).fillna(0)
    people[col] = people[col] + people['to']
    
    del people['to']
        
return people.T

def roundn(n):
'''
构建初始模型
考虑财富值为0,即财富值为0时可以接收 ==> choice的范围是1-100
但不给出 ==> 所以要统计给出的数量 == 接收的数量
'''
# 构建初始财富值
people = pd.DataFrame(index=list(range(1,101)))
people['r0'] = 100

# 构建模型
for i in range(1, n+1): 
    col = 'r' + str(i)
    col0 = 'r' + str(i-1)
    people[col] =  people[col0] - 1
    data_to = pd.Series(np.random.choice(list(range(1,101)), size=100,
      replace=True, p=[]), name='to')
    data_to = data_to.value_counts()
    data_to = pd.DataFrame(data_to)
    people = pd.merge(people, data_to, how='left', left_index=True,
                  right_index=True).fillna(0)
    people[col] = people[col] + people['to']
    
    del people['to']
        
return people.T

def roundm(n):
'''
构建努力人生模型
'''
# 构建初始财富值
people = pd.DataFrame(index=list(range(1,101)))
people['r0'] = 100
person_id= [1, 11, 21, 31, 41, 51, 61, 71, 81, 91] # 努力的Id
# 构建概率
p = [0.899/90 for i in range(100)]
for i in person_id:
p[i-1] = 0.0101

# 构建模型
for i in range(1, n+1): 
    col = 'r' + str(i)
    col0 = 'r' + str(i-1)
    people[col] = people[col0] - 1
    data_to = pd.Series(np.random.choice(list(range(1,101)), size=100,
      replace=True, p=p), name='to')
    data_to = data_to.value_counts()
    data_to = pd.DataFrame(data_to)
    people = pd.merge(people, data_to, how='left', left_index=True,
                  right_index=True).fillna(0)
    people[col] = people[col] + people['to']
    
    del people['to']
        
return people.T

def graph(data, title):
'''
绘制柱状图 == 表排序
'''
plt.figure(figsize=(10, 5))
data.plot(kind='bar', color='gray', edgecolor='gray', figsize=(10, 5))
plt.xlabel('Player Id')
plt.ylabel('Forturn')
plt.title(title)
plt.savefig(title + '.jpg', dpi=200)

def lst():
'''
生产绘制图表数据的行数
'''
lst1 = [x for x in range(0, 100, 10)]
lst2 = [x for x in range(100, 1000, 100)]
lst3 = [x for x in range(1000, 17001, 400)]

return lst1 + lst2 + lst3

def forturn_std(data):
'''
计算每一轮的财富标准差
'''
lst = []
for i in range(17001):
dat = data.iloc[i]
std = dat.std()
lst.append(std)

s = pd.Series(lst)

return s

def line_graph(data, title):
'''
绘制折线图
'''
fig = plt.figure(figsize=(10,5))
plt.plot(data, color='red')
plt.grid(linestyle='--', color='gray', alpha=0.6, axis='both')
plt.xlim([0, 17000])
plt.ylim([0, 150])
plt.title(title)
plt.savefig(title + '.jpg', dpi=400)

def sign_pc(data):
'''
负债id标记
'''
data = pd.DataFrame(data)
data['color'] = 'gray'
data['color'][data['r6200'] < 0] = 'red'
del data['r6200']

return data

if name == 'main':

# 运行初始模型 得到模型数据
r17 = roundn(17000)

# 绘制图表 -- 不排序
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表\初始不排序'
os.chdir(path)

lst = lst()

for i in lst:
    title = 'Round' + str(i)
    #data = r17.iloc[i]
    #graph(data, title)

# 绘制图表 -- 排序
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表\初始排序'
os.chdir(path)
for i in lst:
    title = 'Round' + str(i)
    data = r17.iloc[i]
    data = data.sort_values(ascending=True)
    graph(data, title)

# 运行借贷模型,得到数据
ri17 = roundi(17000)

# 绘制图表
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表\允许借贷'
os.chdir(path)
for i in lst:
    title = 'Round' + str(i)
    data = ri17.iloc[i]
    data = data.sort_values(ascending=True)
    graph(data, title)
    
    
# 调用计算函数,获取标准差
data_std = forturn_std(ri17)
# 绘制图表
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表'
os.chdir(path)
line_graph(data_std, '财富标准差曲线')

# 35岁破产往后逆袭情况  6200次
data_6200 = ri17.iloc[6200]
id_pc =data_6200[data_6200 < 0].index.tolist()
# 对负债id进行标记
id_sign = sign_pc(data_6200)
# 绘制图表
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表\负债逆袭'
os.chdir(path)

for i in range(6200, 17000, 500):
    title = 'Round' + str(i)
    col = 'r' + str(i)
    data = ri17.iloc[i]
    data = pd.DataFrame(data)
    data1 = pd.merge(data, id_sign, how='right', left_index=True, right_index=True)
    data1 = data1.sort_values(by=col, ascending=True)
    fig = plt.figure(figsize=(10,5))
    data1[col].plot(kind='bar', color=data1['color'], figsize=(10,5))
    plt.xlabel('Player Id')
    plt.ylabel('Forturn')
    plt.title(title)
    plt.savefig(title + '.jpg', dpi=200)
    
# 运行努力人生模型,得到数据
rm17 = roundm(17000)
# 对努力id进行标记
id_nl = [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
id_nl_sign = pd.Series('gray', index=range(1, 101), name='color')
for i in id_nl:
    id_nl_sign[i] = 'red'
id_nl_sign = pd.DataFrame(id_nl_sign)

# 绘制图表
path = r'C:\Users\pj2063150\Desktop\项目\项目13社会财富分配问题模拟\图表\努力人生'
os.chdir(path)

for i in lst:
    title = 'Round' + str(i)
    col = 'r' + str(i)
    data = rm17.iloc[i]
    data = pd.DataFrame(data)
    data = pd.merge(data, id_nl_sign, how='right', left_index=True, right_index=True)
    data = data.sort_values(by=col, ascending=True)
    fig = plt.figure(figsize=(10,5))
    data[col].plot(kind='bar', color=data['color'], figsize=(10,5))
    plt.xlabel('Player Id')
    plt.ylabel('Forturn')
    plt.title(title)
    plt.savefig(title + '.jpg', dpi=200) 

print('Finished')
’’’

努力人生.jpg

负债逆袭

财富标准差曲线.jpg

你可能感兴趣的:(项目07_社会财富分配问题模拟)