Revision | 122e257ab677afde702863fd5c1bf7e8b20206e2 (tree) |
---|---|
Zeit | 2024-09-04 22:41:45 |
Autor | Lorenzo Isella <lorenzo.isella@gmai...> |
Commiter | Lorenzo Isella |
ChatGPT translation of my R code to calculate the kpi by DG grow.
@@ -0,0 +1,46 @@ | ||
1 | +import pandas as pd | |
2 | +import matplotlib.pyplot as plt | |
3 | + | |
4 | +# Define the Herfindahl-Hirschman Index (HHI) function | |
5 | +def hhi_index(x): | |
6 | + y = x / x.sum() | |
7 | + res = (y**2).sum() | |
8 | + return res | |
9 | + | |
10 | +# Load the dataset | |
11 | +df = pd.read_csv("../../input/scb_data_for_figures-19-02-2024.tar.gz", compression='gzip') | |
12 | + | |
13 | +# Clean column names (convert to lowercase and replace spaces with underscores) | |
14 | +df.columns = df.columns.str.lower().str.replace(' ', '_') | |
15 | + | |
16 | +# Group by 'expenditure_year' and 'member_state_2_letter_codes' and summarize | |
17 | +df_hhi = (df.groupby(['expenditure_year', 'member_state_2_letter_codes']) | |
18 | + .agg(exp_eur_bn=('aid_element_eur_bn', 'sum'), | |
19 | + ms_gdp_eur_bn=('gdp_eur_bn', 'first')) | |
20 | + .reset_index()) | |
21 | + | |
22 | +# Group by 'expenditure_year', calculate shares, and then calculate HHI | |
23 | +df_hhi = (df_hhi.groupby('expenditure_year') | |
24 | + .apply(lambda x: pd.Series({ | |
25 | + 'hhi_aid': hhi_index(x['exp_eur_bn'] / x['exp_eur_bn'].sum()) * 1e4, | |
26 | + 'hhi_gdp': hhi_index(x['ms_gdp_eur_bn'] / x['ms_gdp_eur_bn'].sum()) * 1e4 | |
27 | + })) | |
28 | + .reset_index()) | |
29 | + | |
30 | + | |
31 | +# Plot hhi_aid against expenditure_year (First Plot) | |
32 | +plt.figure(figsize=(10, 6)) | |
33 | +## plt.plot(df_hhi['hhi_aid'], df_hhi['expenditure_year'], 'g-', label='HHI Aid vs Year (reversed)') # Green line for reverse plot | |
34 | +plt.plot(df_hhi['expenditure_year'], df_hhi['hhi_aid'], 'b-', label='Year vs HHI Aid') # Blue line for standard plot | |
35 | + | |
36 | +plt.plot(df_hhi['expenditure_year'], df_hhi['hhi_gdp'], 'b-', label='Year vs HHIGDP') # Blue line for standard plot | |
37 | + | |
38 | + | |
39 | +# Add labels and title | |
40 | +plt.xlabel('Expenditure Year') | |
41 | +plt.ylabel('HHI Aid') | |
42 | +plt.title('HHI Aid Over Time') | |
43 | + | |
44 | +# Display the legend and plot | |
45 | +plt.legend() | |
46 | +plt.show() |