November 11, 2023
Statistics with Python
This is the code I used in my MA thesis to create an Alliance Network plot.
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
from networkx.drawing.nx_pylab import draw_networkx_nodes, draw_networkx_edges, draw_networkx_labels, draw_networkx_edge_labels
import scipy as sp
f1=open("alliance_dyad_yearly.csv","r",encoding="utf-8")
f2=open("sanctions.csv","r",encoding="utf-8")
txt=f1.readlines()
lst=[]
for i in txt:
i=i.strip("\n").split(",")
m=(i[0],i[1],float(i[2]),float(i[3]))
lst.append(m)
sanc=f2.readlines()
lst2=[]
for i in sanc:
i=i.strip("\n").split(",")
n=(i[0],i[1],float(i[2]))
lst2.append(n)
f1.close()
f2.close()
distances_by_dyad = {'Country_A': [], 'Country_C': [], 'Year': [], 'Distance': []}
graphs_by_year = {}
for alliance in lst:
year = alliance[3]
if year not in graphs_by_year:
graphs_by_year[year] = nx.Graph()
graphs_by_year[year].add_edge(alliance[0], alliance[1], weight=alliance[2])
for dyad in lst2:
country_A, country_C, target_year = dyad
if target_year in graphs_by_year:
G = graphs_by_year[target_year]
try:
weighted_distance = nx.shortest_path_length(G, source=country_A, target=country_C, weight='weight')
distances_by_dyad['Country_A'].append(country_A)
distances_by_dyad['Country_C'].append(country_C)
distances_by_dyad['Year'].append(target_year)
distances_by_dyad['Distance'].append(weighted_distance)
except nx.NetworkXNoPath:
distances_by_dyad['Country_A'].append(country_A)
distances_by_dyad['Country_C'].append(country_C)
distances_by_dyad['Year'].append(target_year)
distances_by_dyad['Distance'].append(float('inf'))
df_distances = pd.DataFrame(distances_by_dyad)
df_distances.to_csv('distances.csv', index=False)
target_year_plot = 2003
G_plot = graphs_by_year[target_year_plot]
pos = nx.random_layout(G_plot, seed=44)
pos['United States of America']=(0,0)
node_sizes=[800*G_plot.degree(node) for node in G_plot.nodes]
edge_weights = [G_plot[u][v]['weight'] for u,v in G_plot.edges]
plt.figure(figsize=(150, 120))
nx.draw(G_plot, pos, with_labels=True, font_weight='bold', node_size=node_sizes, node_color="skyblue", font_size=80, edgecolors='white', linewidths=1, edge_color='grey', alpha=0.8)
plt.title(f'Alliance Network for US Economic Sanctions Targets, {target_year_plot}', y=0.95, fontsize=120, fontweight='bold', alpha=0.9)
plt.savefig('alliance_network_plot.png')
plt.show()
April 17, 2023
Python automation
During my experience as the class monitor and TA, I frequently need to gather and submit files.
Ensuring proper formatting is essential but often times tedious.
So I created this python script to help me automatically formats files as needed.