-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinalScript_CDPCompanies.py
More file actions
2312 lines (1585 loc) · 84.9 KB
/
Copy pathFinalScript_CDPCompanies.py
File metadata and controls
2312 lines (1585 loc) · 84.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import pathlib
import math
## functions used to remove duplicate company entries from the different company profile datasets; combines all profiles for one year into a single dataset
import ProcessDuplicates
# includes Interpolation function used in making time series
import useful_functions
from scipy.interpolate import interp1d
# main functions for cleaning, regression and initiating time series
import CDPCompanies_functions
# used in regression for data selection
from sklearn.linear_model import LinearRegression
dir_data = 'data/2023'
# importing PBL Current Policies scenario; annual change from this time series is used in interpolation step
PBL_CurrentPolicies = pd.read_excel(r''+dir_data+'/input/GP_CurPol.xlsx', sheet_name="data")
PBL_CurrentPolicies_GlobalEmissions=PBL_CurrentPolicies.copy()
PBL_CurrentPolicies_GlobalEmissions = PBL_CurrentPolicies[(PBL_CurrentPolicies['Region']=="World") & (PBL_CurrentPolicies['Variable']=="Emissions|Kyoto Gases")]
annual_change_PBL_IMAGE=float(PBL_CurrentPolicies_GlobalEmissions['2030']/PBL_CurrentPolicies_GlobalEmissions['2020'])**(1/(1-(2030-2020)))-1
# SET YEARS OF DATASETS TO USE
years = ['2018', '2019', '2020', '2021', '2022']
# <h2> Remove Duplicates from Input Files </h2>
# In[3]:
# Run function to process duplicates in input data files by profile and data year
# Outputs single file per year with all profiles; used as input for next step
# ProcessDuplicates.main()
# <h2> Apply Main Cleaning, Selection & Interpolation/Extrapolation Functions </h2>
# In[5]:
## Loop that processes the single year files using imported functions by:
## 1) Cleaning the data
## 2) Combining inventory and target data
## 3) Selecting whether target or inventory data should be used for each company
## 4) Creating time series from each company's base year, MRY and target year emissions through interpolation
final_selections = []
all_series = []
mry_calc = 'mry_interpolate' ## 'mry_standard', 'mry_interpolate'
for year in years:
## clean all profile/year combos
cleaned_combined = CDPCompanies_functions.company_import_cleaning(year, mry_calc)
# cleaned_combined.to_excel(r''+dir_data+'/output/TESTING/NewScopeCalc_CleanedCombined_'+year+'.xlsx')
if mry_calc == 'mry_standard':
cleaned_combined.to_excel(r''+dir_data+'/output/Intermediate/CleanedCombined_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
cleaned_combined.to_excel(r''+dir_data+'/output/Intermediate/CleanedCombined_'+year+'_MRYInterpolation.xlsx')
## use regression to select whether the target or the inventory data is used for each company
data_selected = CDPCompanies_functions.target_inventory_regression(cleaned_combined)
# data_selected.to_excel(r''+dir_data+'/output/TESTING/NewScopeCalc_DataSelected_'+year+'.xlsx')
if mry_calc == 'mry_standard':
data_selected.to_excel(r''+dir_data+'/output/Intermediate/DataSelected_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
data_selected.to_excel(r''+dir_data+'/output/Intermediate/DataSelected_'+year+'_MRYInterpolation.xlsx')
final_selections.append(data_selected)
## set parameters for the time series function
extrapolation = 'PBL_IMAGE'
last_milestone = '1990'
## create time series out of the selected data and interpolate between years
year_series = CDPCompanies_functions.time_series(data_selected)
# year_series.to_excel(r''+dir_data+'/output/TESTING/NewScopeCalc_TimeSeries'+year+'.xlsx')
if mry_calc == 'mry_standard':
year_series.to_excel(r''+dir_data+'/output/Intermediate/UncutTimeSeries_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
year_series.to_excel(r''+dir_data+'/output/Intermediate/UncutTimeSeries_'+year+'_MRYInterpolation.xlsx')
year_columns = list(range(2018, 2051))
info_columns = ['account_id', 'organization_target', 'profile', 'reporting_year', 'selected', 'nr_targets', 'base_year','target_year_1', 'targeted_reduction_1', 'target_year_2',
'targeted_reduction_2', 'target_year_3', 'targeted_reduction_3', 'target_year_4', 'targeted_reduction_4', 'target_year_5', 'targeted_reduction_5', 'by_em_final',
'mry_em_final', 'ty1_em_final', 'ty2_em_final', 'ty3_em_final', 'ty4_em_final', 'ty5_em_final']
## Only keep most relevant columns for the final time series appended to all_series list
slice_columns = info_columns + year_columns
## return data frames with only the emissions time series and most relevant company information
## Cut time series for each reporting year down to only necessary columns and years 2020 - 2050
all_series.append(year_series.loc[:,slice_columns])
# if mry_calc == 'mry_standard':
# cleaned_combined.to_excel(r''+dir_data+'/output/OLD/Intermediate/CleanedCombined_'+year+'_MRYStandard.xlsx')
# data_selected.to_excel(r''+dir_data+'/output/OLD/Intermediate/DataSelected_'+year+'_MRYStandard.xlsx')
# year_series.to_excel(r''+dir_data+'/output/OLD/Intermediate/UncutTimeSeries_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# cleaned_combined.to_excel(r''+dir_data+'/output/OLD/Intermediate/CleanedCombined_'+year+'_MRYInterpolation.xlsx')
# data_selected.to_excel(r''+dir_data+'/output/OLD/Intermediate/DataSelected_'+year+'_MRYInterpolation.xlsx')
# year_series.to_excel(r''+dir_data+'/output/OLD/Intermediate/UncutTimeSeries_'+year+'_MRYInterpolation.xlsx')
# In[6]:
## Check the number of data frames produced
## Should equal number of years from top of script
len(all_series)
# <h2> Check company counts after each processing step </h2>
# In[2]:
# Count number of companies in each data set for input files
# input_years = []
# for year in years:
# input_prof1 = pd.read_excel(r''+dir_data+'/input/IKEA_NSA_abs_er_'+year+'_prof1_vF.xlsx', sheet_name='Sheet 1')
# input_prof2 = pd.read_excel(r''+dir_data+'/input/IKEA_NSA_abs_er_'+year+'_prof2_vF.xlsx', sheet_name='Sheet 1')
# input_prof4 = pd.read_excel(r''+dir_data+'/input/IKEA_NSA_abs_er_'+year+'_prof4_vF.xlsx', sheet_name='Sheet 1')
# input_list = [input_prof1, input_prof2, input_prof4]
# input_concat = pd.concat(input_list, ignore_index=True)
# input_years.append(input_concat)
# input_rows = []
# for x in input_years:
# input_rows.append(x.shape[0])
# In[4]:
# Count number of companies in each data set after removing duplicate entries for companies
# processed_years = []
# for year in years:
# processed = pd.read_excel(r''+dir_data+'/processed/IKEA_NSA_abs_er_'+year+'_vF.xlsx', sheet_name='Sheet 1')
# processed_years.append(processed)
# processduplicates_rows = []
# for x in processed_years:
# processduplicates_rows.append(x.shape[0])
# In[7]:
# Count number of companies in each data set after cleaning and combining
# cleanedcombined = []
# for year in years:
# cc = pd.read_excel(r''+dir_data+'/output/Intermediate/CleanedCombined_'+year+'_MRYInterpolation.xlsx')
# cleanedcombined.append(cc)
# cc_rows = []
# for x in cleanedcombined:
# cc_rows.append(x.shape[0])
# In[8]:
# Count number of companies in each data set after data selection regression step
# dataselected_rows = []
# for x in final_selections:
# dataselected_rows.append(x.shape[0])
# In[9]:
# Create dataframe with total company counts in each dataset after different processing steps
# company_counts = pd.DataFrame()
# company_counts['Input Rows'] = input_rows
# company_counts['Post ProcessDuplicates'] = processduplicates_rows
# company_counts['Post CleanedCombined'] = cc_rows
# company_counts['Post Data Selection'] = dataselected_rows
# df_index = pd.Index(years)
# company_counts.set_index(df_index, inplace=True)
# company_counts.to_excel(r''+dir_data+'/output/Intermediate/CompanyCounts.xlsx')
# <h2> All Companies Processing </h2>
# In[13]:
## Sort companies by account id in prep for next steps
for s in all_series:
s.sort_values(by=['account_id'])
# In[14]:
## Sum emissions from all companies in each year; divide by 1000000 to convert to Mt
## This is used as the basis for the ambition pathways
for a in all_series:
a.loc['Total'] = a.loc[:,2018:2050].sum(axis=0).div(1000000)
# In[15]:
## Export time series 2018 - 2050 for each reporting year
for (a, year) in zip(all_series, years):
if mry_calc == 'mry_standard':
a.to_excel(r''+dir_data+'/output/Final/ALL_TimeSeries_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
a.to_excel(r''+dir_data+'/output/Final/ALL_TimeSeries_'+year+'_MRYInterpolation.xlsx')
# if mry_calc == 'mry_standard':
# a.to_excel(r''+dir_data+'/output/OLD/Final/ALL_TimeSeries_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# a.to_excel(r''+dir_data+'/output/OLD/Final/ALL_TimeSeries_'+year+'_MRYInterpolation.xlsx')
# <h3> Check Top 10 from each dataset </h3>
# In[10]:
## Select the top 10 companies from each data set in terms of base year emissions and mry emissions
# top10_by = []
# top10_mry = []
# for x in final_selections:
# top_by = x.nlargest(n=10, columns=['by_em_final'])
# top_mry = x.nlargest(n=10, columns=['mry_em_final'])
# top10_by.append(top_by[['account_id','organization_target', 'selected', 'by_em_final']])
# top10_mry.append(top_mry[['account_id', 'organization_target', 'selected', 'mry_em_final']])
# In[11]:
## Export top 10 companies OVERALL, REGARDLESS OF SECTOR in terms of base year emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_BY_STANDARD.xlsx') as writer:
# for i in range(len(years)):
# top10_by[i].to_excel(writer, sheet_name=str(years[i]))
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_BY_INTERPOLATE.xlsx') as writer:
# for i in range(len(years)):
# top10_by[i].to_excel(writer, sheet_name=str(years[i]))
# In[12]:
## Export top 10 companies OVERALL, REGARDLESS OF SECTOR in terms of mry emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_MRY_STANDARD.xlsx') as writer:
# for i in range(len(years)):
# top10_mry[i].to_excel(writer, sheet_name=str(years[i]))
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_MRY_INTERPOLATE.xlsx') as writer:
# for i in range(len(years)):
# top10_mry[i].to_excel(writer, sheet_name=str(years[i]))
# <h2> Overlapping Companies Processing </h2>
# In[16]:
## Filter out overlapping companies (companies who reported in all reporting years)
## from: https://statisticsglobe.com/merge-list-pandas-dataframes-python
from functools import reduce
overlapping_companies = reduce(lambda left, right:
pd.merge(left , right,
on = ["account_id"],
how = "inner"),
all_series)
overlapping_list = list(overlapping_companies['account_id'])
overlapping_series = []
for s in all_series:
overlapping = s[s['account_id'].isin(overlapping_list)]
overlapping_series.append(overlapping)
# In[20]:
## check for duplicate account ids in all reporting years
for s in all_series:
print(s[s['account_id'].duplicated(keep=False)])
# In[21]:
## Sum emissions from overlapping companies in each year; divide by 1000000 to convert to Mt
for o in overlapping_series:
o.loc['Total'] = o.loc[:,2018:2050].sum(axis=0).div(1000000)
# In[22]:
## Export time series from each reporting year for overlapping companies
for (o, year) in zip(overlapping_series, years):
if mry_calc == 'mry_standard':
o.to_excel(r''+dir_data+'/output/Final/OV_TimeSeries_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
o.to_excel(r''+dir_data+'/output/Final/OV_TimeSeries_'+year+'_MRYInterpolation.xlsx')
# if mry_calc == 'mry_standard':
# o.to_excel(r''+dir_data+'/output/OLD/Final/OV_TimeSeries_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# o.to_excel(r''+dir_data+'/output/OLD/Final/OV_TimeSeries_'+year+'_MRYInterpolation.xlsx')
# <h3> Check Top 10 from each dataset </h3>
# In[17]:
# ov_top10_by = []
# ov_top10_mry = []
# for i in overlapping_series:
# top_by = i.nlargest(n=10, columns=['by_em_final'])
# top_mry = i.nlargest(n=10, columns=['mry_em_final'])
# ov_top10_by.append(top_by[['account_id','organization_target', 'selected', 'by_em_final']])
# ov_top10_mry.append(top_mry[['account_id', 'organization_target', 'selected', 'mry_em_final']])
# In[18]:
## Export top 10 companies OVERALL, REGARDLESS OF SECTOR in terms of base year emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/OVTop10_BY_STANDARD.xlsx') as writer:
# for i in range(len(years)):
# ov_top10_by[i].to_excel(writer, sheet_name=str(years[i]))
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/OVTop10_BY_INTERPOLATE.xlsx') as writer:
# for i in range(len(years)):
# ov_top10_by[i].to_excel(writer, sheet_name=str(years[i]))
# In[19]:
## Export top 10 companies OVERALL, REGARDLESS OF SECTOR in terms of mry emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/OVTop10_MRY_STANDARD.xlsx') as writer:
# for i in range(len(years)):
# ov_top10_mry[i].to_excel(writer, sheet_name=str(years[i]))
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/OVTop10_MRY_INTERPOLATE.xlsx') as writer:
# for i in range(len(years)):
# ov_top10_mry[i].to_excel(writer, sheet_name=str(years[i]))
# <h2> Ambition Pathways Graph </h2>
# In[23]:
## VISUALISATION OF AMBITION PATHWAYS
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(9, 6))
fig.suptitle('Ambition Pathways')
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
x = list(range(2020, 2051))
legend_years = ['2018', '2019', '2020', '2021', '2022']
y = overlapping_series
z = all_series
for i in range(len(y)):
## Plot OVERLAPPING companies
ax1.plot(x, y[i].loc['Total', 2020:2050], label=legend_years[i])
## Plot ALL companies
ax2.plot(x, z[i].loc['Total', 2020:2050], label=legend_years[i])
ax1.legend()
ax2.legend()
ax1.title.set_text('Overlapping Companies')
ax1.set_ylabel('Emissions (Mt CO2e)')
ax1. set_xlabel('Years')
ax2.title.set_text('All Companies')
ax2.set_xlabel('Years')
fig.tight_layout()
# plt.savefig(r''+dir_data+'/output/TESTING/NewScopeCalc_AP.png')
if mry_calc == 'mry_standard':
plt.savefig(r''+dir_data+'/output/Figures/NEW_AmbitionPathways_MRYStandard.png')
elif mry_calc == 'mry_interpolate':
plt.savefig(r''+dir_data+'/output/Figures/NEW_AmbitionPathways_MRYInterpolation.png')
plt.savefig(r''+dir_data+'/output/ForDesigner/AmbitionPathways.eps', format='eps')
# <h3> Export Excel files for designer </h3>
# In[24]:
## Export Excel files for designer
ap_all_data = []
for i in range(len(legend_years)):
data = z[i].loc['Total', 2020:2050]
ap_all_data.append(data)
ap_ov_data = []
for i in range(len(legend_years)):
data = y[i].loc['Total', 2020:2050]
ap_ov_data.append(data)
# In[25]:
ap_all = pd.concat(ap_all_data, axis=1)
ap_ov = pd.concat(ap_ov_data, axis=1)
# In[26]:
ap_all.columns = [legend_years]
ap_ov.columns = [legend_years]
# In[27]:
with pd.ExcelWriter(r''+dir_data+'/output/ForDesigner/AmbitionPathways.xlsx') as writer:
ap_all.to_excel(writer, sheet_name='All Companies')
ap_ov.to_excel(writer, sheet_name='Overlapping Companies')
# <h2> IEA Sector Mapping </h2>
# In[28]:
all_sectors = []
## Mapping of 'Primary activity' values from C5 Emissions Methodology sheets to IEA sectors: Chemical and petrochemical, Iron and steel or Non-metallic minerals
sector_mapping = {'Iron & steel': 'Iron and steel', 'Basic plastics':'Chemical and petrochemical', 'Agricultural chemicals':'Chemical and petrochemical', 'Inorganic base chemicals':'Chemical and petrochemical',
'Specialty chemicals':'Chemical and petrochemical', 'Other base chemicals':'Chemical and petrochemical', 'Oil & gas refining':'Chemical and petrochemical',
'Glass products':'Non-metallic minerals', 'Cement':'Non-metallic minerals', 'Other non-metallic minerals':'Non-metallic minerals', 'Ceramics':'Non-metallic minerals'}
# import C5_EmissionsMethodology files for all relevant years
for year in years:
## THE C5 EMISSIONS FILES WERE TRASNFERRED TO THE '20221014/INPUT' FOLDER
c5_file = pd.read_excel(r''+dir_data+'/input/C5_EmissionsMethodology_'+year+'.xlsx')
c5_file.rename(columns={'Account number':'account_id'}, inplace=True)
c5_file.sort_values(by=['account_id'])
c5_crop = c5_file[['account_id','Organization','Primary activity', 'Primary sector', 'Primary industry']]
# c5_crop['IEA sector'] = c5_crop['Primary sector'].map(sector_mapping, na_action='ignore')
c5_crop['IEA sector'] = c5_crop['Primary activity'].map(sector_mapping, na_action='ignore')
all_sectors.append(c5_crop)
# <h3> Overlapping Companies Sector Mapping </h3>
# In[29]:
ovcompanies_industryagg = []
ovcompanies_sectoragg = []
ovcompanies_sectorlist = []
## Will apply the 2018 primary activity/IEA sector and primary industry classifications from each company for consistency
## (Otherwise the same companies change these designations over reporting years, confounding results)
c5_2018 = all_sectors[0]
# attach c5_EmissionsMethodology to respective time series, by year, FOR OVERLAPPING COMPANIES
for x in overlapping_series:
## merge 2018 C5 classification scheme to each year's time series data
industry_merge = x.merge(c5_2018, how='left', on='account_id')
ovcompanies_sectorlist.append(industry_merge)
## group by Primary industry, as defined by CDP
industry_agg = industry_merge.groupby(by=['Primary industry']).sum().loc[:,2020:2050].div(1000000)
## add columns to calculate summary stats
industry_agg.loc['Total'] = industry_agg.sum(axis=0)
percent_change = industry_agg.loc[:,2020:2050].pct_change(axis=1)
industry_agg.loc['Annual Percentage Change'] = percent_change.loc['Total']*100
ovcompanies_industryagg.append(industry_agg)
## group by assigned IEA sector, according to IEA sector mapping
sector_agg = industry_merge.groupby(by=['IEA sector']).sum().loc[:,2020:2050].div(1000000)
## add columns to calculate summary stats
sector_agg.loc['Total'] = sector_agg.sum(axis=0)
percent_change = sector_agg.loc[:,2020:2050].pct_change(axis=1)
sector_agg.loc['Annual Percentage Change'] = percent_change.loc['Total']*100
ovcompanies_sectoragg.append(sector_agg)
# In[34]:
# Output industry aggregated emissions for OVERLAPPING companies
for (il, year) in zip(ovcompanies_industryagg, years):
if mry_calc == 'mry_standard':
il.to_excel(r''+dir_data+'/output/Final/IndustryAgg_OV'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
il.to_excel(r''+dir_data+'/output/Final/IndustryAgg_OV'+year+'_MRYInterpolation.xlsx')
for (sl, year) in zip(ovcompanies_sectoragg, years):
if mry_calc == 'mry_standard':
sl.to_excel(r''+dir_data+'/output/Final/IEASectorAgg_OV_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
sl.to_excel(r''+dir_data+'/output/Final/IEASectorAgg_OV_'+year+'_MRYInterpolation.xlsx')
# for (il, year) in zip(ovcompanies_industryagg, years):
# if mry_calc == 'mry_standard':
# il.to_excel(r''+dir_data+'/output/OLD/Final/IndustryAgg_OV'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# il.to_excel(r''+dir_data+'/output/OLD/Final/IndustryAgg_OV'+year+'_MRYInterpolation.xlsx')
# for (sl, year) in zip(ovcompanies_sectoragg, years):
# if mry_calc == 'mry_standard':
# sl.to_excel(r''+dir_data+'/output/OLD/Final/IEASectorAgg_OV_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# sl.to_excel(r''+dir_data+'/output/OLD/Final/IEASectorAgg_OV_'+year+'_MRYInterpolation.xlsx')
# <h4> Check Top 10 </h4>
# In[30]:
## Select top 10 companies in each sector, in each year, in terms of by and mry emissions, for OVERLAPPING companies
# ov_sectors_topby = []
# ov_sectors_topmry = []
# for i in ovcompanies_sectorlist:
# for s in ['Chemical and petrochemical', 'Iron and steel', 'Non-metallic minerals']:
# i_s = i[i['IEA sector'] == s]
# top_by = i_s[['account_id', 'selected', 'by_em_final', 'IEA sector']].nlargest(n=10, columns=['by_em_final'])
# top_mry = i_s[['account_id', 'selected', 'mry_em_final', 'IEA sector']].nlargest(n=10, columns=['mry_em_final'])
# ov_sectors_topby.append(top_by)
# ov_sectors_topmry.append(top_mry)
# In[31]:
## Concatenate top for each sector together by year
# ts_by_2018 = pd.concat(ov_sectors_topby[0:3])
# ts_by_2019 = pd.concat(ov_sectors_topby[3:6])
# ts_by_2020 = pd.concat(ov_sectors_topby[6:9])
# ts_by_2021 = pd.concat(ov_sectors_topby[9:12])
# ts_by_2022 = pd.concat(ov_sectors_topby[12:15])
# ts_mry_2018 = pd.concat(ov_sectors_topmry[0:3])
# ts_mry_2019 = pd.concat(ov_sectors_topmry[3:6])
# ts_mry_2020 = pd.concat(ov_sectors_topmry[6:9])
# ts_mry_2021 = pd.concat(ov_sectors_topmry[9:12])
# ts_mry_2022 = pd.concat(ov_sectors_topmry[12:15])
# In[32]:
## Export top 10 companies PER SECTOR for OVERLAPPING companies in terms of base year emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_OVSECTORS_BY_STANDARD.xlsx') as writer:
# ts_by_2018.to_excel(writer, sheet_name='2018')
# ts_by_2019.to_excel(writer, sheet_name='2019')
# ts_by_2020.to_excel(writer, sheet_name='2020')
# ts_by_2021.to_excel(writer, sheet_name='2021')
# ts_by_2022.to_excel(writer, sheet_name='2022')
# if mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_OVSECTORS_BY_INTERPOLATE.xlsx') as writer:
# ts_by_2018.to_excel(writer, sheet_name='2018')
# ts_by_2019.to_excel(writer, sheet_name='2019')
# ts_by_2020.to_excel(writer, sheet_name='2020')
# ts_by_2021.to_excel(writer, sheet_name='2021')
# ts_by_2022.to_excel(writer, sheet_name='2022')
# In[33]:
## Export top 10 companies PER SECTOR for OVERLAPPING companies in terms of mry emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_OVSECTORS_MRY_STANDARD.xlsx') as writer:
# ts_mry_2018.to_excel(writer, sheet_name='2018')
# ts_mry_2019.to_excel(writer, sheet_name='2019')
# ts_mry_2020.to_excel(writer, sheet_name='2020')
# ts_mry_2021.to_excel(writer, sheet_name='2021')
# ts_mry_2022.to_excel(writer, sheet_name='2022')
# if mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_OVSECTORS_MRY_INTERPOLATE.xlsx') as writer:
# ts_mry_2018.to_excel(writer, sheet_name='2018')
# ts_mry_2019.to_excel(writer, sheet_name='2019')
# ts_mry_2020.to_excel(writer, sheet_name='2020')
# ts_mry_2021.to_excel(writer, sheet_name='2021')
# ts_mry_2022.to_excel(writer, sheet_name='2022')
# <h3> All Companies Sector Mapping </h3>
# In[35]:
allcompanies_industryagg = []
allcompanies_sectoragg = []
allcompanies_sectorlist = []
## attach c5_EmissionsMethodology to respective time series, by year, FOR ALL COMPANIES
for x, c5 in zip(all_series, all_sectors):
## merge C5 classification scheme to each year's time series data
industry_merge = x.merge(c5, how='left', on='account_id')
allcompanies_sectorlist.append(industry_merge)
## group by Primary industry, as defined by CDP
industry_agg = industry_merge.groupby(by=['Primary industry']).sum().loc[:,2020:2050].div(1000000)
## add columns to calculate summary stats
# industry_agg.loc[:, 'No. of companies reporting'] = c5.loc[:,'Primary industry'].value_counts()
industry_agg.loc['Total'] = industry_agg.sum(axis=0)
percent_change = industry_agg.loc[:,2020:2050].pct_change(axis=1)
industry_agg.loc['Annual Percentage Change'] = percent_change.loc['Total']*100
allcompanies_industryagg.append(industry_agg)
## group by assigned sector, according to IEA sector mapping
sector_agg = industry_merge.groupby(by=['IEA sector']).sum().loc[:,2020:2050].div(1000000)
## add columns to calculate summary stats
# sector_agg.loc[:, 'No. of companies reporting'] = c5.loc[:,'IEA sector'].value_counts()
sector_agg.loc['Total'] = sector_agg.sum(axis=0)
sector_change = sector_agg.loc[:,2020:2050].pct_change(axis=1)
sector_agg.loc['Total Annual Percentage Change'] = sector_change.loc['Total']*100
sector_agg.loc['C&P Annual Percentage Change'] = sector_change.loc['Chemical and petrochemical']*100
sector_agg.loc['I&S Annual Percentage Change'] = sector_change.loc['Iron and steel']*100
sector_agg.loc['NM Annual Percentage Change'] = sector_change.loc['Non-metallic minerals']*100
allcompanies_sectoragg.append(sector_agg)
# In[36]:
## Output industry and IEA sector aggregated emissions for ALL companies as inidividual files
for (il, year) in zip(allcompanies_industryagg, years):
if mry_calc == 'mry_standard':
il.to_excel(r''+dir_data+'/output/Final/IndustryAgg_ALL_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
il.to_excel(r''+dir_data+'/output/Final/IndustryAgg_ALL_'+year+'_MRYInterpolation.xlsx')
for (sl, year) in zip(allcompanies_sectoragg, years):
if mry_calc == 'mry_standard':
sl.to_excel(r''+dir_data+'/output/Final/IEASectorAgg_ALL_'+year+'_MRYStandard.xlsx')
elif mry_calc == 'mry_interpolate':
sl.to_excel(r''+dir_data+'/output/Final/IEASectorAgg_ALL_'+year+'_MRYInterpolation.xlsx')
# for (il, year) in zip(allcompanies_industryagg, years):
# if mry_calc == 'mry_standard':
# il.to_excel(r''+dir_data+'/output/OLD/Final/IndustryAgg_ALL_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# il.to_excel(r''+dir_data+'/output/OLD/Final/IndustryAgg_ALL_'+year+'_MRYInterpolation.xlsx')
# for (sl, year) in zip(allcompanies_sectoragg, years):
# if mry_calc == 'mry_standard':
# sl.to_excel(r''+dir_data+'/output/OLD/Final/IEASectorAgg_ALL_'+year+'_MRYStandard.xlsx')
# elif mry_calc == 'mry_interpolate':
# sl.to_excel(r''+dir_data+'/output/OLD/Final/IEASectorAgg_ALL_'+year+'_MRYInterpolation.xlsx')
# <h4> Check Top 10 </h4>
# In[37]:
## Select top 10 companies in each sector, in each year, in terms of by and mry emissions, for ALL companies
# all_sectors_topby = []
# all_sectors_topmry = []
# for i in allcompanies_sectorlist:
# for s in ['Chemical and petrochemical', 'Iron and steel', 'Non-metallic minerals']:
# i_s = i[i['IEA sector'] == s]
# top_by = i_s[['account_id', 'selected', 'by_em_final', 'IEA sector']].nlargest(n=10, columns=['by_em_final'])
# top_mry = i_s[['account_id', 'selected', 'mry_em_final', 'IEA sector']].nlargest(n=10, columns=['mry_em_final'])
# all_sectors_topby.append(top_by)
# all_sectors_topmry.append(top_mry)
# In[38]:
## Concatenate top companies for each sector together by year (3 sectors per year)
# ta_by_2018 = pd.concat(all_sectors_topby[0:3])
# ta_by_2019 = pd.concat(all_sectors_topby[3:6])
# ta_by_2020 = pd.concat(all_sectors_topby[6:9])
# ta_by_2021 = pd.concat(all_sectors_topby[9:12])
# ta_by_2022 = pd.concat(all_sectors_topby[12:15])
# ta_mry_2018 = pd.concat(all_sectors_topmry[0:3])
# ta_mry_2019 = pd.concat(all_sectors_topmry[3:6])
# ta_mry_2020 = pd.concat(all_sectors_topmry[6:9])
# ta_mry_2021 = pd.concat(all_sectors_topmry[9:12])
# ta_mry_2022 = pd.concat(all_sectors_topmry[12:15])
# In[39]:
## Export top 10 companies from ALL companies PER SECTOR in terms of base year emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_ALLSECTORS_BY_STANDARD.xlsx') as writer:
# ta_by_2018.to_excel(writer, sheet_name='2018')
# ta_by_2019.to_excel(writer, sheet_name='2019')
# ta_by_2020.to_excel(writer, sheet_name='2020')
# ta_by_2021.to_excel(writer, sheet_name='2021')
# ta_by_2022.to_excel(writer, sheet_name='2022')
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_ALLSECTORS_BY_INTERPOLATE.xlsx') as writer:
# ta_by_2018.to_excel(writer, sheet_name='2018')
# ta_by_2019.to_excel(writer, sheet_name='2019')
# ta_by_2020.to_excel(writer, sheet_name='2020')
# ta_by_2021.to_excel(writer, sheet_name='2021')
# ta_by_2022.to_excel(writer, sheet_name='2022')
# In[40]:
## Export top 10 companies from ALL companies PER SECTOR in terms of mry emissions for each reporting year
# if mry_calc == 'mry_standard':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_ALLSECTORS_MRY_STANDARD.xlsx') as writer:
# ta_mry_2018.to_excel(writer, sheet_name='2018')
# ta_mry_2019.to_excel(writer, sheet_name='2019')
# ta_mry_2020.to_excel(writer, sheet_name='2020')
# ta_mry_2021.to_excel(writer, sheet_name='2021')
# ta_mry_2022.to_excel(writer, sheet_name='2022')
# elif mry_calc == 'mry_interpolate':
# with pd.ExcelWriter(r''+dir_data+'/output/Intermediate/Top10_ALLSECTORS_MRY_INTERPOLATE.xlsx') as writer:
# ta_mry_2018.to_excel(writer, sheet_name='2018')
# ta_mry_2019.to_excel(writer, sheet_name='2019')
# ta_mry_2020.to_excel(writer, sheet_name='2020')
# ta_mry_2021.to_excel(writer, sheet_name='2021')
# ta_mry_2022.to_excel(writer, sheet_name='2022')
# <h2> Export Combined Final Datasets </h2>
# In[41]:
## Output all companies in each year with assigned IEA sector
## Outputs to Excel file with each year as a separate sheet within the file
sectors = ['Chemical and petrochemical', 'Iron and steel', 'Non-metallic minerals']
with pd.ExcelWriter(r''+dir_data+'/output/ALLCOMPANIES_IEASECTORS.xlsx') as writer:
for i in range(len(allcompanies_sectorlist)):
for s in sectors:
allcompanies_sectorlist[i][allcompanies_sectorlist[i]['IEA sector'] == s].to_excel(writer, sheet_name=years[i])
# In[42]:
## Calculate average annual change for different IEA sectors by year
cp_change = []
is_change = []
nm_change = []
sectorchange_avg = pd.DataFrame(index=years, columns=['C&P', 'I&S', 'NM'])
for x in allcompanies_sectoragg:
cp = x.loc['C&P Annual Percentage Change'].mean()
cp_change.append(cp)
i_s = x.loc['I&S Annual Percentage Change'].mean()
is_change.append(i_s)
nm = x.loc['NM Annual Percentage Change'].mean()
nm_change.append(nm)
sectorchange_avg['C&P'] = cp_change
sectorchange_avg['I&S'] = is_change
sectorchange_avg['NM'] = nm_change
# In[43]:
## Calculate average annual change for each year's aggregated ambition pathway
for (x, o) in zip(all_series, overlapping_series):
all_pct = x.loc[:,2020:2050].pct_change(axis=1)
ov_pct = o.loc[:,2020:2050].pct_change(axis=1)
x.loc['Annual Percentage Change'] = all_pct.loc['Total']*100
o.loc['Annual Percentage Change'] = ov_pct.loc['Total']*100
annualchange_avg = pd.DataFrame(index=years, columns=['Overlapping Companies', 'All Companies'])
all_change = []
ov_change = []
for i in range(len(years)):
ac = all_series[i].loc['Annual Percentage Change'].mean()
oc = overlapping_series[i].loc['Annual Percentage Change'].mean()
all_change.append(ac)
ov_change.append(oc)
annualchange_avg['Overlapping Companies'] = ov_change
annualchange_avg['All Companies'] = all_change
# In[98]:
data_a = []
data_o = []
## Take emissions values from ambition pathways at key years and convert to GIGATONNES
for (a, o) in zip(all_series, overlapping_series):
em_a = a.loc['Total',[2020,2030,2040,2050]].div(1000)
data_a.append(em_a)
em_o = o.loc['Total',[2020,2030,2040,2050]].div(1000)
data_o.append(em_o)
# In[99]:
em_all = pd.DataFrame(data=data_a,index=years)
em_ov = pd.DataFrame(data=data_o,index=years)
for f in [em_all, em_ov]:
f.loc[:, 'Percent Change 2020 - 2050'] = ((f.loc[:, 2020] - f.loc[:, 2050])/f.loc[:, 2020])*100
# In[100]:
## Output aggregated ambition pathways for all companies IEA sector, with separate sheets by year
with pd.ExcelWriter(r''+dir_data+'/output/Combined_AmbitionPathways.xlsx') as writer:
annualchange_avg.to_excel(writer, sheet_name='Average Annual Change by Year')
em_all.to_excel(writer, sheet_name='EmissionsSnapshot_AllCompanies')
em_ov.to_excel(writer, sheet_name='EmissionsSnapshot_OVCompanies')
for i in range(len(all_series)):
all_series[i].to_excel(writer, sheet_name='ALL_'+years[i])
for i in range(len(overlapping_series)):
overlapping_series[i].to_excel(writer, sheet_name='OV_'+years[i])
# <h2> Create Target & Annual Reduction Tables: All & Overlapping Companies </h2>
# In[47]:
## Functions to calculat annual reductions for different target categories based on distance from disclosure year
def annual_reductions_short(frame, year):
t0 = int(year)
T = int(year) + 5
EM_t0 = frame.loc['Total', t0]
EM_T = frame.loc['Total', T]
annual_reduction = -1*((EM_T/EM_t0)**(1/(T-t0))-1)
return annual_reduction*100
def annual_reductions_medium(frame, year):
t0 = int(year) + 6
T = int(year) + 15
EM_t0 = frame.loc['Total', t0]
EM_T = frame.loc['Total', T]
annual_reduction = -1*((EM_T/EM_t0)**(1/(T-t0))-1)
return annual_reduction*100
def annual_reductions_long(frame, year):
t0 = int(year) + 16
T = 2050
EM_t0 = frame.loc['Total', t0]
EM_T = frame.loc['Total', T]
annual_reduction = -1*((EM_T/EM_t0)**(1/(T-t0))-1)
return annual_reduction*100
# In[48]:
ar_short = []
ar_medium = []
ar_long = []
for (a, y) in zip(all_series, years):
ars = annual_reductions_short(a, y)
arm = annual_reductions_medium(a, y)
arl = annual_reductions_long(a, y)
ar_short.append(ars)
ar_medium.append(arm)
ar_long.append(arl)
ser_list = []
for x in [ar_short, ar_medium, ar_long]:
ser = pd.Series(x, index=years)
ser_list.append(ser)
summary_table_all = pd.concat(ser_list, axis=1, keys=['Annual Reduction Short-term Targets', 'Annual Reduction Medium-term Targets', 'Annual Reduction Long-term Targets'])
# In[49]:
or_short = []
or_medium = []
or_long = []
for (o, y) in zip(overlapping_series, years):
ors = annual_reductions_short(o, y)
orm = annual_reductions_medium(o, y)
orl = annual_reductions_long(o, y)
or_short.append(ors)
or_medium.append(orm)
or_long.append(orl)
ser2_list = []
for x in [or_short, or_medium, or_long]:
ser2 = pd.Series(x, index=years)
ser2_list.append(ser2)
summary_table_ov = pd.concat(ser2_list, axis=1, keys=['Annual Reduction Short-term Targets', 'Annual Reduction Medium-term Targets', 'Annual Reduction Long-term Targets'])
# In[50]:
## Create summary tables of companies/targets for all companies and number of companies/targets for overlapping companies in each reporting year
for (s, year) in zip(all_series, years):
summary_table_all.loc[year, 'Total companies'] = s.shape[0]
summary_table_all.loc[year, 'Total targets'] = s['nr_targets'].sum()
## Target length is defined as follows:
## Short targets: targets where the target year is listed as being between the disclosure year and 5 years later than the discloure year
## Medium targets: targets where the target year is listed as being between 6 and 15 years later than the disclosure year
## Long targets: targets where the target year is listed as being greater than 15 years later than the disclosure year
summary_table_all.loc[year, 'N_Short targets'] = (s['target_year_1'].between(int(year),int(year)+5, inclusive='both').sum() +
s['target_year_2'].between(int(year),int(year)+5, inclusive='both').sum() +
s['target_year_3'].between(int(year),int(year)+5, inclusive='both').sum() +
s['target_year_4'].between(int(year),int(year)+5, inclusive='both').sum() +
s['target_year_5'].between(int(year),int(year)+5, inclusive='both').sum())
summary_table_all.loc[year, 'N_Medium targets'] = (s['target_year_1'].between(int(year)+6,int(year)+15, inclusive='both').sum() +
s['target_year_2'].between(int(year)+6,int(year)+15, inclusive='both').sum() +
s['target_year_3'].between(int(year)+6,int(year)+15, inclusive='both').sum() +
s['target_year_4'].between(int(year)+6,int(year)+15, inclusive='both').sum() +
s['target_year_5'].between(int(year)+6,int(year)+15, inclusive='both').sum())
summary_table_all.loc[year, 'N_Long targets'] = ((s['target_year_1'] > int(year)+15).sum() +
(s['target_year_2'] > int(year)+15).sum() +