python投票一致性指数(IVC)实现代码
毕业论文中用于计算联合国会员国间在联合国大会上的投票一致性(IVC)
import pandas as pd import sqlite3 import networkx as nx import time import numpy as np def gen_dict(sql):#建立投票数据字典 votedict={} votedict['all']={} for c in cntylist: votedict['all'][c]={} votedict['all'][c]['yes']=[] votedict['all'][c]['noyes']=[] votedict['all'][c]['qq']=[] votedict['all'][c]['no']=[] votedict['all'][c]['all']=[] for y in [1992,2001,2010]: votedict[y]={} for c in cntylist: votedict[y][c]={} votedict[y][c]['yes']=[] votedict[y][c]['noyes']=[] votedict[y][c]['qq']=[] votedict[y][c]['no']=[] votedict[y][c]['all']=[] for c in cntylist: c1=c r1sql='select rcid, Country, vote, year from data where vote<4 and Country= \'%s\'' % c1 + sql rec1=pd.read_sql(r1sql ,conn) yeslist=rec1[rec1['vote']==1]['rcid'].tolist() noyeslist=rec1[(rec1['vote']==2)|(rec1['vote']==3)]['rcid'].tolist() nolist=rec1[rec1['vote']==3]['rcid'].tolist() qqlist=rec1[rec1['vote']==2]['rcid'].tolist() votedict['all'][c]['yes']=yeslist votedict['all'][c]['noyes']=noyeslist votedict['all'][c]['qq']=qqlist votedict['all'][c]['no']=nolist votedict['all'][c]['all']=rec1['rcid'].tolist() for y in [1992,2001,2010]: for c in cntylist: c1=c yearsql='and year>= %d and year< %d'%(y,y+8) r1sql='select rcid, Country, vote, year from data where vote<4 and Country= \'%s\'' % c1+yearsql+sql rec1=pd.read_sql(r1sql ,conn) yeslist=rec1[rec1['vote']==1]['rcid'].tolist() noyeslist=rec1[(rec1['vote']==2)|(rec1['vote']==3)]['rcid'].tolist() nolist=rec1[rec1['vote']==3]['rcid'].tolist() qqlist=rec1[rec1['vote']==2]['rcid'].tolist() votedict[y][c]['yes']=yeslist votedict[y][c]['noyes']=noyeslist votedict[y][c]['qq']=qqlist votedict[y][c]['no']=nolist votedict[y][c]['all']=rec1['rcid'].tolist() print(sql,y,'生成该年份数据') print(sql,'数据字典已经生成') return votedict def ivc_gen_new(thedict,c1,c2):#基于字典计算两国间IVC c1yes= thedict[c1]['yes'] c1no= thedict[c1]['no'] c1noyes=thedict[c1]['noyes'] c1qq=thedict[c1]['qq'] c2yes= thedict[c2]['yes'] c2no=thedict[c2]['no'] c2noyes=thedict[c2]['noyes'] c2qq=thedict[c2]['qq'] c1all=thedict[c1]['all'] c2all=thedict[c2]['all'] flist=[x for x in c1yes if x in c2yes]+[x for x in c1qq if x in c2qq]+[x for x in c1no if x in c2no] glist=[x for x in c1qq if x in c2yes+c2no]+[x for x in c2qq if x in c1yes+c1no] f=len(set(flist)) g=len(set(glist)) t=len(set([c for c in c1all if c in c2all])) try: ivc=(f+0.5*g)/t except: ivc=0 return ivc
IVC方法参考
Turner J. Party and constituency: Pressures on congress[M]. Baltimore: The Johns Hopkins Press, 1952.