Script 769: Pacing New Campaign Calculations

Purpose

This Python script solves the problem of calculating various metrics and values for pacing and budget allocation in a digital advertising campaign.

To Elaborate

The script takes input data from a primary data source and performs calculations to determine the pacing and budget allocation for each campaign. The key business rules and calculations include:

  • Calculating the total publication cost, clicks, impressions, and views for each campaign based on the specified start and end dates.
  • Determining the auto pacing cycle start and end dates based on the campaign start and end dates, as well as the current date.
  • Calculating the total days, auto pacing cycle publication cost, impressions, clicks, and views for each campaign.
  • Calculating the auto pacing cycle days, days elapsed, and days remaining.
  • Calculating the auto pacing cycle daily target spend per impressions/views.
  • Calculating the auto pacing cycle expected to date and pacing.
  • Determining the delivery status of each campaign based on the auto pacing cycle threshold and goal type.
  • Calculating the total target spend per impressions/views for each campaign.
  • Calculating the total days elapsed and total daily target for each campaign.
  • Calculating the total expected to date and total pacing for each campaign.
  • Determining the auto pacing cycle target remaining spend per impressions/views.
  • Calculating the pacing cycle daily allocation spend per impressions/views.
  • Calculating the recommended daily budget for each campaign.

Walking Through the Code

  1. The script starts by importing the necessary libraries and defining the necessary constants.
  2. It then creates two dataframes, df1 and df2, from the input data.
  3. The script performs various data transformations and calculations using pandas functions and custom functions.
  4. The calculated values are assigned to the corresponding columns in the df1 dataframe.
  5. Finally, the script prints the updated dataframe and assigns it to the outputDf variable.

Vitals

  • Script ID : 769
  • Client ID / Customer ID: 1306927187 / 60270139
  • Action Type: Bulk Upload (Preview)
  • Item Changed: Campaign
  • Output Columns: Account, Campaign, Auto. Pacing Cycle Clicks, Auto. Pacing Cycle Days, Auto. Pacing Cycle Days Elapsed, Auto. Pacing Cycle Days Remaining, Auto. Pacing Cycle End Date, Auto. Pacing Cycle Expected to Date, Auto. Pacing Cycle Impr., Auto. Pacing Cycle Pacing, Auto. Pacing Cycle Pub. Cost, Auto. Pacing Cycle Start Date, Delivery Status, Recommended Daily Budget, Todays Date, Total Clicks, Total Daily Target, Total Days, Total Days Elapsed, Total Expected to Date, Total Impressions, Total Pacing, Total Pub Cost, Total Target (Spend/Impr./Views), Total Views, Auto. Pacing Cycle Threshold, Auto. Pacing Cycle Views
  • Linked Datasource: M1 Report
  • Reference Datasource: None
  • Owner: ascott@marinsoftware.com (ascott@marinsoftware.com)
  • Created by ascott@marinsoftware.com on 2024-03-06 22:09
  • Last Updated by ascott@marinsoftware.com on 2024-03-19 18:45
> See it in Action

Python Code

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
## Infinite Digital Pacing Script
## name: New Campaign Calculations
## description:
##  
## 
## author: Jesus A. Garza
## created: 2024-02-06
## 

today = datetime.datetime.now().date()

# primary data source and columns
inputDf = dataSourceDict["1"]
RPT_COL_CAMPAIGN = 'Campaign'
RPT_COL_DATE = 'Date'
RPT_COL_ACCOUNT = 'Account'
RPT_COL_BRAND = 'Brand'
RPT_COL_GOAL = 'Goal'
RPT_COL_PACING__START_DATE = 'Pacing - Start Date'
RPT_COL_PACING__END_DATE = 'Pacing - End Date'
RPT_COL_TARGET_IMPR_PER_SPENDVIEWS = 'Target (Impr/Spend/Views)'
RPT_COL_CPM_RESTRAINT = 'CPM Restraint'
RPT_COL_CPC_RESTRAINT = 'CPC Restraint'
RPT_COL_CAMPAIGN_TYPE = 'Campaign Type'
RPT_COL_CAMPAIGN_STATUS = 'Campaign Status'
RPT_COL_SBA_TRAFFIC = 'SBA Traffic'
RPT_COL_TOTAL_PUB_COST = 'Total Pub Cost'
RPT_COL_TOTAL_IMPRESSIONS = 'Total Impressions'
RPT_COL_TOTAL_CLICKS = 'Total Clicks'
RPT_COL_TOTAL_VIEWS = 'Total Views'
RPT_COL_PACING_CYCLE_PUB_COST = 'Pacing Cycle Pub Cost'
RPT_COL_PACING_CYCLE_IMPRESSIONS = 'Pacing Cycle Impressions'
RPT_COL_PACING_CYCLE_CLICKS = 'Pacing Cycle Month Clicks'
RPT_COL_PACING_CYCLE_VIEWS = 'Pacing Cycle Views'
RPT_COL_AUTO_PACING_CYCLE_START_DATE = 'Auto. Pacing Cycle Start Date'
RPT_COL_AUTO_PACING_CYCLE_END_DATE = 'Auto. Pacing Cycle End Date'
RPT_COL_TODAYS_DATE = 'Todays Date'
RPT_COL_AUTO_PACING_CYCLE_DAYS = 'Auto. Pacing Cycle Days'
RPT_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED = 'Auto. Pacing Cycle Days Elapsed'
RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING = 'Auto. Pacing Cycle Days Remaining'
RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS = 'Auto. Pacing Daily Target (Spend/Impressions/Views)'
RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE = 'Auto. Pacing Cycle Expected to Date'
RPT_COL_AUTO_PACING_CYCLE_PACING = 'Auto. Pacing Cycle Pacing'
RPT_COL_AUTO_PACING_CYCLE_THRESHOLD = 'Auto. Pacing Cycle Threshold'
RPT_COL_AUTO_PACING_CYCLE_CLICKS = 'Auto. Pacing Cycle Clicks'
RPT_COL_AUTO_PACING_CYCLE_IMPR = 'Auto. Pacing Cycle Impr.'
RPT_COL_AUTO_PACING_CYCLE_PUB_COST = 'Auto. Pacing Cycle Pub. Cost'
RPT_COL_AUTO_PACING_CYCLE_VIEWS = 'Auto. Pacing Cycle Views'
RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS = 'Total Target (Spend/Impr./Views)'
RPT_COL_TOTAL_DAYS = 'Total Days'
RPT_COL_TOTAL_DAYS_ELAPSED = 'Total Days Elapsed'
RPT_COL_TOTAL_DAILY_TARGET = 'Total Daily Target'
RPT_COL_TOTAL_EXPECTED_TO_DATE = 'Total Expected to Date'
RPT_COL_TOTAL_PACING = 'Total Pacing'
RPT_COL_DELIVERY_STATUS = 'Delivery Status'
RPT_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS = 'Auto. Pacing Cycle Target Remaining (Spend/Impr./Views)'
RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS = 'Auto. Pacing Cycle Daily Allocation (Spend/Impr./Views)'
RPT_COL_RECOMMENDED_DAILY_BUDGET = 'Recommended Daily Budget'
RPT_COL_IMPR = 'Impr.'
RPT_COL_CLICKS = 'Clicks'
RPT_COL_PUB_COST = 'Pub. Cost $'
RPT_COL_VIDEO_VIEWS = 'Video Views'

# output columns and initial values
BULK_COL_ACCOUNT = 'Account'
BULK_COL_CAMPAIGN = 'Campaign'
BULK_COL_AUTO_PACING_CYCLE_CLICKS = 'Auto. Pacing Cycle Clicks'
BULK_COL_AUTO_PACING_CYCLE_DAYS = 'Auto. Pacing Cycle Days'
BULK_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED = 'Auto. Pacing Cycle Days Elapsed'
BULK_COL_AUTO_PACING_CYCLE_DAYS_REMAINING = 'Auto. Pacing Cycle Days Remaining'
BULK_COL_AUTO_PACING_CYCLE_END_DATE = 'Auto. Pacing Cycle End Date'
BULK_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE = 'Auto. Pacing Cycle Expected to Date'
BULK_COL_AUTO_PACING_CYCLE_IMPR = 'Auto. Pacing Cycle Impr.'
BULK_COL_AUTO_PACING_CYCLE_PACING = 'Auto. Pacing Cycle Pacing'
BULK_COL_AUTO_PACING_CYCLE_PUB_COST = 'Auto. Pacing Cycle Pub. Cost'
BULK_COL_AUTO_PACING_CYCLE_START_DATE = 'Auto. Pacing Cycle Start Date'
BULK_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS = 'Auto. Pacing Cycle Target Remaining (Spend/Impr./Views)'
BULK_COL_AUTO_PACING_CYCLE_THRESHOLD = 'Auto. Pacing Cycle Threshold'
BULK_COL_AUTO_PACING_CYCLE_VIEWS = 'Auto. Pacing Cycle Views'
BULK_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS = 'Auto. Pacing Daily Target (Spend/Impressions/Views)'
BULK_COL_DELIVERY_STATUS = 'Delivery Status'
BULK_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS = 'Auto. Pacing Cycle Daily Allocation (Spend/Impr./Views)'
BULK_COL_RECOMMENDED_DAILY_BUDGET = 'Recommended Daily Budget'
BULK_COL_TODAYS_DATE = 'Todays Date'
BULK_COL_TOTAL_CLICKS = 'Total Clicks'
BULK_COL_TOTAL_DAILY_TARGET = 'Total Daily Target'
BULK_COL_TOTAL_DAYS = 'Total Days'
BULK_COL_TOTAL_DAYS_ELAPSED = 'Total Days Elapsed'
BULK_COL_TOTAL_EXPECTED_TO_DATE = 'Total Expected to Date'
BULK_COL_TOTAL_IMPRESSIONS = 'Total Impressions'
BULK_COL_TOTAL_PACING = 'Total Pacing'
BULK_COL_TOTAL_PUB_COST = 'Total Pub Cost'
BULK_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS = 'Total Target (Spend/Impr./Views)'
BULK_COL_TOTAL_VIEWS = 'Total Views'
outputDf[BULK_COL_AUTO_PACING_CYCLE_CLICKS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_DAYS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_END_DATE] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_IMPR] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_PACING] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_PUB_COST] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_START_DATE] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_THRESHOLD] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_VIEWS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_DELIVERY_STATUS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_RECOMMENDED_DAILY_BUDGET] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TODAYS_DATE] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_CLICKS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_DAILY_TARGET] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_DAYS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_DAYS_ELAPSED] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_EXPECTED_TO_DATE] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_IMPRESSIONS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_PACING] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_PUB_COST] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS] = "<<YOUR VALUE>>"
outputDf[BULK_COL_TOTAL_VIEWS] = "<<YOUR VALUE>>"

print(inputDf.columns)

# Create DataFrame 1
data_df1 = inputDf[[RPT_COL_DATE, RPT_COL_CAMPAIGN, RPT_COL_ACCOUNT, RPT_COL_TARGET_IMPR_PER_SPENDVIEWS, RPT_COL_PACING__START_DATE, RPT_COL_PACING__END_DATE, RPT_COL_GOAL, RPT_COL_CLICKS, RPT_COL_IMPR, RPT_COL_CAMPAIGN_STATUS]].copy()

# Create DataFrame 2
data_df2 = inputDf[[RPT_COL_DATE, RPT_COL_ACCOUNT, RPT_COL_CAMPAIGN, RPT_COL_PUB_COST, RPT_COL_CLICKS, RPT_COL_IMPR, RPT_COL_VIDEO_VIEWS]]

# Create DataFrame 1 and DataFrame 2
df1 = pd.DataFrame(data_df1)
df2 = pd.DataFrame(data_df2)

# Convert 'Pacing - Start Date' and 'Pacing - End Date' columns to datetime
df1[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1[RPT_COL_PACING__START_DATE])
df1[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1[RPT_COL_PACING__END_DATE])
df2[RPT_COL_DATE] = pd.to_datetime(df2[RPT_COL_DATE])

# Populate the new columns in df1 with the sum of values from df2 for each campaign
for index, row in df1.iterrows():
    campaign = row[RPT_COL_CAMPAIGN]
    account = row[RPT_COL_ACCOUNT]
    start_date = row[RPT_COL_PACING__START_DATE]
    end_date = row[RPT_COL_PACING__END_DATE]
    
    # Filter df2 for the specific campaign and within the date range
    filtered_data = df2[(df2[RPT_COL_ACCOUNT] == account) & (df2[RPT_COL_CAMPAIGN] == campaign) & (df2[RPT_COL_DATE] >= start_date) & (df2[RPT_COL_DATE] <= end_date)]
    
    # Calculate the sum and assign them to the new columns in df1
    df1.loc[index, RPT_COL_TOTAL_PUB_COST] = filtered_data[RPT_COL_PUB_COST].sum().round(2)
    df1.loc[index, RPT_COL_TOTAL_CLICKS] = filtered_data[RPT_COL_CLICKS].sum().round(2)
    df1.loc[index, RPT_COL_TOTAL_IMPRESSIONS] = filtered_data[RPT_COL_IMPR].sum().round(2)
    df1.loc[index, RPT_COL_TOTAL_VIEWS] = filtered_data[RPT_COL_VIDEO_VIEWS].sum().round(2)

# Drop duplicates based on the 'Campaign' column
df1_deduplicated = df1.drop_duplicates(subset=[RPT_COL_CAMPAIGN]).copy()

# Display the updated DataFrame
print(df1_deduplicated)


##Todays date
df1_deduplicated[RPT_COL_TODAYS_DATE] = today

##Auto. Pacing Cycle Start Date 
##Formula: =IF(A2<>"",IF(AND(YEAR(E2)=YEAR(Y2),MONTH(Y2)=MONTH(E2)),E2,IF(Y2>F2,"",IF(AH2<=31,E2,EOMONTH(Y2,-1)+1))),"")
##Python
# Ensure the relevant columns are in datetime format
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

def calculate_auto_pacing_cycle_start_date(row):
    start_date = row['Pacing - Start Date'] 
    today_date = pd.to_datetime('today').normalize()  # Make today's date timezone naive
    end_date = row['Pacing - End Date']

    if pd.notnull(start_date) and pd.notnull(today_date):
        if start_date.year == today_date.year and start_date.month == today_date.month:
            result = start_date
        elif today_date > end_date:  
            return pd.NaT
        else:
            result = today_date.replace(day=1)  # Default to the first day of the current month
        
        return result
    else:
        return pd.NaT

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = df1_deduplicated.apply(calculate_auto_pacing_cycle_start_date, axis=1)


##Auto. Pacing Cycle End Date   
##Formula: =IF(A2<>"",IF(Y2>F2,"",IF(AND(YEAR(F2)=YEAR(Y2),MONTH(Y2)=MONTH(F2)),F2,IF(AH2<=31,E2,EOMONTH(Y2,0)))),"")
##Python
# Ensure the relevant columns are in datetime format
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')

def calculate_auto_pacing_cycle_end_date(row):
    if pd.notnull(row['Campaign']):  # Check if campaign identifier is not empty
        end_date = row['Pacing - End Date']
        today_date = pd.to_datetime('today').normalize()  # Make today's date timezone naive
        
        if today_date > end_date:
            return ""
        elif end_date.year == today_date.year and end_date.month == today_date.month:
            return end_date
        else:
            # Use MonthEnd to get the end of the current month for today's date
            return pd.offsets.MonthEnd(0).rollforward(today_date)
    else:
        return pd.NaT  # Return Not a Time (NaT) for empty or invalid campaign identifiers

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = df1_deduplicated.apply(calculate_auto_pacing_cycle_end_date, axis=1)


##Total Days    
##Formula: =if(A2<>"",IF(F2-E2+1<1,"",F2-E2+1),"")
##Python 
# Convert date columns to datetime format
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')

def calculate_total_days(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):  
        # Calculate the difference in days, then add 1
        days_diff = (row[RPT_COL_PACING__END_DATE] - row[RPT_COL_PACING__START_DATE]).days + 1
        # Check if the calculated difference is less than 1
        if days_diff < 1:
            return 0  
        else:
            return days_diff
    else:
        return 0  

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_TOTAL_DAYS] = df1_deduplicated.apply(calculate_total_days, axis=1)

##Auto. Pacing Cycle Pub. Cost 
##Formula: =if(A2<>"",sumIFs('Campaign Daily Data'!E:E,'Campaign Daily Data'!B:B,">="&W2,'Campaign Daily Data'!B:B,"<="&X2,'Campaign Daily Data'!A:A,A2),"")
##Python
# Convert date columns to datetime format if not already
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

# Calculate Auto. Pacing Cycle Pub Cost for each row in inputDf
def calculate_auto_pacing_cycle_pub_cost(row):
    if row[RPT_COL_CAMPAIGN] != "":
        start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
        end_date = row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]
        campaign = row[RPT_COL_CAMPAIGN]

        # Filter 'campaign_daily_data' based on the criteria
        filtered_data = df2[
            (df2[RPT_COL_CAMPAIGN] == campaign) & 
            (df2[RPT_COL_DATE] >= start_date) & 
            (df2[RPT_COL_DATE] <= end_date)
        ]

        # Sum the publication costs for the filtered data
        total_pub_cost = filtered_data[RPT_COL_PUB_COST].sum()
        return total_pub_cost
    else:
        return 0 

# Apply the function to each row in 'inputDf' and create a new column for the auto pacing cycle publication cost
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PUB_COST] = df1_deduplicated.apply(calculate_auto_pacing_cycle_pub_cost, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PUB_COST] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PUB_COST].round(2)


##Auto. Pacing Cycle Impr. 
##Formula: =if(A2<>"",sumIFs('Campaign Daily Data'!C:C,'Campaign Daily Data'!B:B,">="&W2,'Campaign Daily Data'!B:B,"<="&X2,'Campaign Daily Data'!A:A,A2),"") 
##Python 
# Convert date columns to datetime format if not already
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

# Calculate Auto. Pacing Cycle Impressions for each row in inputDf
def calculate_auto_pacing_cycle_impressions(row):
    if row[RPT_COL_CAMPAIGN] != "":
        start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
        end_date = row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]
        campaign = row[RPT_COL_CAMPAIGN]

        # Filter 'campaign_daily_data' based on the criteria
        filtered_data = df2[
            (df2[RPT_COL_CAMPAIGN] == campaign) & 
            (df2[RPT_COL_DATE] >= start_date) & 
            (df2[RPT_COL_DATE] <= end_date)
        ]

        # Sum the impressions for the filtered data
        total_impressions = filtered_data[RPT_COL_IMPR].sum()
        return total_impressions
    else:
        return 0 

# Apply the function to each row in 'inputDf' and create a new column for the auto pacing cycle impressions
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_IMPR] = df1_deduplicated.apply(calculate_auto_pacing_cycle_impressions, axis=1)


##Auto. Pacing Cycle Clicks 
##Formula: =if(A2<>"",sumIFs('Campaign Daily Data'!D:D,'Campaign Daily Data'!B:B,">="&W2,'Campaign Daily Data'!B:B,"<="&X2,'Campaign Daily Data'!A:A,A2),"")
##Python 
# Define the column names based on your data source dictionary
# Convert date columns to datetime format if not already
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

# Calculate Auto. Pacing Cycle Clicks for each row in inputDf
def calculate_auto_pacing_cycle_clicks(row):
    if row[RPT_COL_CAMPAIGN] != "":
        start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
        end_date = row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]
        campaign = row[RPT_COL_CAMPAIGN]

        # Filter 'campaign_daily_data' based on the criteria
        filtered_data = df2[
            (df2[RPT_COL_CAMPAIGN] == campaign) & 
            (df2[RPT_COL_DATE] >= start_date) & 
            (df2[RPT_COL_DATE] <= end_date)
        ]

        # Sum the clicks for the filtered data
        total_clicks = filtered_data[RPT_COL_CLICKS].sum()
        return total_clicks
    else:
        return 0  

# Apply the function to each row in 'inputDf' and create a new column for the auto pacing cycle clicks
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_CLICKS] = df1_deduplicated.apply(calculate_auto_pacing_cycle_clicks, axis=1)


##Auto. Pacing Cycle Views  
##Formula: =if(A2<>"",sumIFs('Campaign Daily Data'!F:F,'Campaign Daily Data'!B:B,">="&W2,'Campaign Daily Data'!B:B,"<="&X2,'Campaign Daily Data'!A:A,A2),"")
##Python 
# Convert date columns to datetime format if not already
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

# Calculate Auto. Pacing Cycle Views for each row in inputDf
def calculate_auto_pacing_cycle_views(row):
    if row[RPT_COL_CAMPAIGN] != "":
        start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
        end_date = row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]
        campaign = row[RPT_COL_CAMPAIGN]

        # Filter 'campaign_daily_data' based on the criteria
        filtered_data = df2[
            (df2[RPT_COL_CAMPAIGN] == campaign) & 
            (df2[RPT_COL_DATE] >= start_date) & 
            (df2[RPT_COL_DATE] <= end_date)
        ]

        # Sum the views for the filtered data
        total_views = filtered_data[RPT_COL_VIDEO_VIEWS].sum()
        return total_views
    else:
        return 0  

# Apply the function to each row in 'inputDf' and create a new column for the auto pacing cycle views
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_VIEWS] = df1_deduplicated.apply(calculate_auto_pacing_cycle_views, axis=1)


##Todays Date   
##Formula: =if(A2<>"",today(),"")
##Python: 
#today = datetime.datetime.now(CLIENT_TIMEZONE).date()

##Auto. Pacing Cycle Days   
##Formula: =if(A2<>"",if(X2="","",if(AH2<=31,AH2,(X2-W2)+1)),"")
##Python:
# First, ensure that the dates are in the appropriate datetime format
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')

def calculate_apc_days(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]) and pd.notnull(row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]) and pd.notnull(row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]):
        if row[RPT_COL_TOTAL_DAYS] <= 31:  
            return row[RPT_COL_TOTAL_DAYS]  
        else:
            # Ensure both dates are timezone-naive before subtracting
            start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
            end_date = row[RPT_COL_AUTO_PACING_CYCLE_END_DATE]
            return (end_date - start_date).days + 1
    else:
        return ""
        
# Apply the function row-wise
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAYS] = df1_deduplicated.apply(calculate_apc_days, axis=1)

##Auto. Pacing Cycle Days Elapsed
##Formula: =IF(A2<>"",IF(X2="","",IF(Y2-W2<=0,0,Y2-W2)),"")
##Definition: If campaign column is not blank and Auto. Pacing Cycle Start Date is not blank
##Python: 
# Convert the relevant columns to datetime format, assuming they're not already
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_END_DATE], errors='coerce')  # In case it's needed

def calculate_date_apc_days_elapsed(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):  # Checks if the campaign column is not empty
        start_date = row[RPT_COL_AUTO_PACING_CYCLE_START_DATE]
        today_date = pd.to_datetime(today).normalize()  # Make today's date timezone naive
        
        if pd.isnull(start_date):  # Checks if the calculated start date is empty
            return ""
        # Calculate the difference between the dates in 'today_date' and 'start_date'
        diff = (today_date - start_date).days
        if diff <= 0:  # If the difference is less than or equal to 0
            return 0
        else:
            return diff
    else:
        return ""

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED] = df1_deduplicated.apply(calculate_date_apc_days_elapsed, axis=1)

    
##Auto. Pacing Cycle Days Remaining 
##Formula: =if(A2<>"",IF(Z2-AA2<0,0,Z2-AA2),"")
##Python: 
def calculate_apc_days_remaining(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):
        # Convert the values to numeric types before subtraction
        days = pd.to_numeric(row[RPT_COL_AUTO_PACING_CYCLE_DAYS], errors='coerce')
        days_elapsed = pd.to_numeric(row[RPT_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED], errors='coerce')
        
        # Check if the conversion resulted in NaN (not a number)
        if pd.isnull(days) or pd.isnull(days_elapsed):
            return ""  # Return an empty string or some other appropriate value for your context
        
        # Calculate the difference
        diff = days - days_elapsed
        return max(0, diff)
    else:
        return ""

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] = df1_deduplicated.apply(calculate_apc_days_remaining, axis=1)


##Auto. Pacing Daily Target (Spend, Impressions, Views) 
##Formula: =iferror(IF(D2="ms",G2/Z2,IF(D2="CPM",G2/Z2,IF(D2="CPV",G2/Z2,""))),"")
##Python
def calculate_auto_pacing_daily_target(row):
    try:
        # Since the calculation is the same for all specified campaign types, we directly perform the division
        if row[RPT_COL_GOAL] in ["MS", "CPM", "CPV"]:
            return row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS] / row[RPT_COL_AUTO_PACING_CYCLE_DAYS] if row[RPT_COL_AUTO_PACING_CYCLE_DAYS] != 0 else 0
        else:
            return 0  # Default to 0 for undefined campaign types or other errors
    except:
        return 0  # Safeguard against any other kind of error

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS] = df1_deduplicated.apply(calculate_auto_pacing_daily_target, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS] = df1_deduplicated[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS].round(2)
df1_deduplicated[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS] = df1_deduplicated[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS].astype(str)


##Auto. Pacing Cycle Expected to Date   
##Formula: =if(A2<>"",AC2*AA2,"")
##Python:
def calculate_apc_etd(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):
        # Convert both columns to numeric types, coercing errors to NaN
        daily_target = pd.to_numeric(row[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS], errors='coerce')
        days_elapsed = pd.to_numeric(row[RPT_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED], errors='coerce')
        
        # Check if either value is NaN after conversion
        if pd.isnull(daily_target) or pd.isnull(days_elapsed):
            return 0  # Return 0 or some other appropriate default value
        
        # Perform the multiplication
        return daily_target * days_elapsed
    else:
        return 0  # Return 0 or some other appropriate default value if the campaign is null

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] = df1_deduplicated.apply(calculate_apc_etd, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE].round(2)
#df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE].astype(str)


##Auto. Pacing Cycle Pacing 
##Formula: =IFerror(IF(D2="ms",S2/AD2,IF(D2="CPM",T2/AD2,IF(D2="CPV",V2/AD2,0))),0)
##Python
def calculate_auto_pacing_cycle_pacing(row):
    try:
        # Check campaign type and perform corresponding calculation
        if row[RPT_COL_GOAL] == "MS":
            return row[RPT_COL_AUTO_PACING_CYCLE_PUB_COST] / row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] if row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] != 0 else 0
        elif row[RPT_COL_GOAL] == "CPM":
            return row[RPT_COL_AUTO_PACING_CYCLE_IMPR] / row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] if row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] != 0 else 0
        elif row[RPT_COL_GOAL] == "CPV":
            return row[RPT_COL_AUTO_PACING_CYCLE_VIEWS] / row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] if row[RPT_COL_AUTO_PACING_CYCLE_EXPECTED_TO_DATE] != 0 else 0
        else:
            return 0  
    except:
        return 0  

# Calculate pacing as a percentage and convert to numeric type
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING] = df1_deduplicated.apply(calculate_auto_pacing_cycle_pacing, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING] = pd.to_numeric(df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING], errors='coerce') * 100.0
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING].round(2)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_PACING].astype(str) + '%'


##Auto. Pacing Cycle Threshold  
##Formula: =if(A2<>"",IF(Y2>F2,"Campaign Ended",if(AE2<97%,"Under Pacing",if(AND(AE2<104%,AE2>103%),"Over Pacing",if(AE2>105%,"Severely Overpacing","On Pace")))),"")
##Python
# Convert the relevant columns to datetime format, assuming they're not already
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

def calculate_auto_pacing_cycle_threshold(row):
    today_date = row[RPT_COL_TODAYS_DATE]
    if pd.notnull(row[RPT_COL_CAMPAIGN]):  
        end_date = row[RPT_COL_PACING__END_DATE]

        if end_date is not pd.NaT and today_date > end_date:
            return "Campaign Ended"
        else:
            # Convert pacing to a float by removing the '%' sign and dividing by 100
            pacing_str = row[RPT_COL_AUTO_PACING_CYCLE_PACING].replace('%', '')  # Remove the '%' sign
            pacing = float(pacing_str) / 100.0  # Convert to float and divide by 100
            
            if pacing < 0.97: 
                return "Under Pacing"
            elif 0.97 <= pacing < 1.04:  
                return "On Pace"
            elif 1.04 <= pacing <= 1.05:  
                return "Over Pacing"
            elif pacing > 1.05:  
                return "Severely Overpacing"
            else:
                return "On Pace"
    else:
        return ""

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_THRESHOLD] = df1_deduplicated.apply(calculate_auto_pacing_cycle_threshold, axis=1)


##Total Target (Spend/Impr./Views) 
##Formula: =if(A2<>"",IF(F2-E2+1<=31,G2,(G2/30)*(F2-E2)+1),"")
##Python
# Ensure date columns are in datetime format for calculation
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')

def calculate_total_target(row):
    if row[RPT_COL_CAMPAIGN] != "":  
        # Calculate the duration from the start and end dates
        duration_days = (row[RPT_COL_PACING__END_DATE] - row[RPT_COL_PACING__START_DATE]).days + 1
        # Remove both commas and dollar signs before converting to float
        target_impr_per_spendviews_str = str(row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS]) if pd.notnull(row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS]) else '0'
        target_impr_per_spendviews = float(target_impr_per_spendviews_str.replace(',', '').replace('$', ''))
        if duration_days <= 31:
            return target_impr_per_spendviews
        else:
            return (target_impr_per_spendviews / 30) * duration_days
    else:
        return ""

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS] = df1_deduplicated.apply(calculate_total_target, axis=1)
df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS] = df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS].round(2)
df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS] = df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS].replace(np.nan, '', regex=True)
df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS] = df1_deduplicated[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS].astype(str)

##Total Days    
##Formula: =if(A2<>"",IF(F2-E2+1<1,"",F2-E2+1),"")
##Python 
# Convert date columns to datetime format
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_PACING__END_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__END_DATE], errors='coerce')

def calculate_total_days(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):  
        # Calculate the difference in days, then add 1
        days_diff = (row[RPT_COL_PACING__END_DATE] - row[RPT_COL_PACING__START_DATE]).days + 1
        # Check if the calculated difference is less than 1
        if days_diff < 1:
            return ""
        else:
            return days_diff
    else:
        return ""

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_TOTAL_DAYS] = df1_deduplicated.apply(calculate_total_days, axis=1)


##Total Days Elapsed  
##Formula: =IF(A2<>"",IF(AH2="","",IF(Y2-E2<=0,"",if(Y2-E2>=AH2,AH2,Y2-E2))),"")  
##Python
# Ensure the date columns are in datetime format
df1_deduplicated[RPT_COL_PACING__START_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_PACING__START_DATE], errors='coerce')
df1_deduplicated[RPT_COL_TODAYS_DATE] = pd.to_datetime(df1_deduplicated[RPT_COL_TODAYS_DATE], errors='coerce')

# Define the calculation as a function
def calculate_days_elapsed(row):
    if pd.notnull(row[RPT_COL_CAMPAIGN]):  # Checks if 'A' is not empty
        if pd.isnull(row[RPT_COL_TOTAL_DAYS]):  # Checks if 'AH' is empty
            return ""

        today_date = row[RPT_COL_TODAYS_DATE]
        start_date = row[RPT_COL_PACING__START_DATE]
        
        if start_date is not pd.NaT:
            start_date = pd.to_datetime(start_date.date())  # Convert to Timestamp
        today_date = row[RPT_COL_TODAYS_DATE]

        # Calculate the difference in days between 'Y' and 'E'
        days_diff = (today_date - start_date).days
        if days_diff <= 0:
            return ""
        # Convert RPT_COL_TOTAL_DAYS to an integer before comparison
        total_days = int(row[RPT_COL_TOTAL_DAYS]) if row[RPT_COL_TOTAL_DAYS] != "" else 0
        if days_diff >= total_days:
            return total_days
        else:
            return days_diff
    else:
        return ""

# Apply the function across each row
df1_deduplicated[RPT_COL_TOTAL_DAYS_ELAPSED] = df1_deduplicated.apply(calculate_days_elapsed, axis=1)


##Total Daily Target    
##Formula: =iferror(AG2/AH2,"")
##Python 
# Safe division function to avoid division by zero and handle errors
def safe_division(numerator, denominator):
    try:
        # Convert numerator to a numeric type, coercing errors to NaN
        numerator = pd.to_numeric(numerator, errors='coerce')
        # Check if the denominator is a numeric value and not zero
        if isinstance(denominator, (int, float)) and denominator != 0:
            return numerator / denominator
        else:
            return None  # or return 0 if that's more appropriate for your context
    except ZeroDivisionError:  # In case of division by zero
        return None

# Apply the safe division function to calculate the total daily target
df1_deduplicated[RPT_COL_TOTAL_DAILY_TARGET] = df1_deduplicated.apply(lambda row: safe_division(row[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS], row[RPT_COL_TOTAL_DAYS]), axis=1)
df1_deduplicated[RPT_COL_TOTAL_DAILY_TARGET] = df1_deduplicated[RPT_COL_TOTAL_DAILY_TARGET].round(2)

##Total Expected to Date    
##Formula: =if(AI2<>"",AI2*AJ2,"")
##Python 
# Calculate the total expected to date using the conditions described
def calculate_expected_to_date(row):
    # Ensure that both values are numeric before multiplying
    total_days_elapsed = pd.to_numeric(row[RPT_COL_TOTAL_DAYS_ELAPSED], errors='coerce')
    total_daily_target = pd.to_numeric(row[RPT_COL_TOTAL_DAILY_TARGET], errors='coerce')
    
    # Check if either value is NaN after conversion (which could happen if coercion failed)
    if pd.isnull(total_days_elapsed) or pd.isnull(total_daily_target):
        return 0  # Return 0 or NaN if that's more appropriate for your context
    
    # Perform the multiplication
    return total_days_elapsed * total_daily_target

# Apply the function to each row in the DataFrame
df1_deduplicated[RPT_COL_TOTAL_EXPECTED_TO_DATE] = df1_deduplicated.apply(calculate_expected_to_date, axis=1)
df1_deduplicated[RPT_COL_TOTAL_EXPECTED_TO_DATE] = df1_deduplicated[RPT_COL_TOTAL_EXPECTED_TO_DATE].round(2)


##Total Pacing  
##Formula: =IFerror(IF(D2="ms",O2/AK2,IF(D2="CPM",P2/AK2,IF(D2="CPV",R2/AK2,""))),"")
##Python
# Function to calculate Total Pacing as a percentage
def calculate_total_pacing(row):
    try:
        # Goal type is 'ms'
        if row[RPT_COL_GOAL] == 'MS':
            return row[RPT_COL_TOTAL_PUB_COST] / row[RPT_COL_TOTAL_EXPECTED_TO_DATE] if row[RPT_COL_TOTAL_EXPECTED_TO_DATE] != 0 else ""
        # Goal type is 'CPM'
        elif row[RPT_COL_GOAL] == 'CPM':
            return row[RPT_COL_TOTAL_IMPRESSIONS] / row[RPT_COL_TOTAL_EXPECTED_TO_DATE] if row[RPT_COL_TOTAL_EXPECTED_TO_DATE] != 0 else ""
        # Goal type is 'CPV'
        elif row[RPT_COL_GOAL] == 'CPV':
            return row[RPT_COL_TOTAL_VIEWS] / row[RPT_COL_TOTAL_EXPECTED_TO_DATE] if row[RPT_COL_TOTAL_EXPECTED_TO_DATE] != 0 else ""
        else:
            return ""
    except:
        # Handles division by zero or any other calculation error
        return ""

# Calculate pacing as a percentage and convert to numeric type
df1_deduplicated[RPT_COL_TOTAL_PACING] = df1_deduplicated.apply(calculate_total_pacing, axis=1)
df1_deduplicated[RPT_COL_TOTAL_PACING] = pd.to_numeric(df1_deduplicated[RPT_COL_TOTAL_PACING], errors='coerce') * 100.0
df1_deduplicated[RPT_COL_TOTAL_PACING] = df1_deduplicated[RPT_COL_TOTAL_PACING].round(2)
df1_deduplicated[RPT_COL_TOTAL_PACING] = df1_deduplicated[RPT_COL_TOTAL_PACING].fillna('')
df1_deduplicated[RPT_COL_TOTAL_PACING] = df1_deduplicated[RPT_COL_TOTAL_PACING].apply(lambda x: f"{int(x)}%" if x != '' else x)

##Delivery Status   
##Formula: =iferror(IF(AND(Y3>F3, D3="CPM", P3/AG3<97%), "Underdelivery",
# IF(AND(Y3>F3, D3="CPM", OR(P3/AG3>115%, P3-AG3>50000)), "Overdelivery",
#    IF(AND(Y3>F3, D3="CPM", P3/AG3>=97%, P3/AG3<=115%), "On Target",
#      IF(AND(Y3>F3, D3="MS", O3/AG3<100%), "Underdelivery",
#        IF(AND(Y3>F3, D3="MS", OR(O3/AG3>103%, O3-AG3>500)), "Overdelivery",
#          IF(AND(Y3>F3, D3="MS", O3/AG3>=100%, O3/AG3<=103%), "On Target",
#            IF(AND(Y3>F3, D3="CPV", R3/AG3<100%), "Underdelivery",
#             IF(AND(Y3>F3, D3="CPV", OR(R3/AG3>103%, R3-AG3>50000)), "Overdelivery",
#                IF(AND(Y3>F3, D3="CPV", R3/AG3>=100%, R3/AG3<=103%), "On Target", "")
##Python
def calculate_delivery_status(row):
    try:
        if row[RPT_COL_AUTO_PACING_CYCLE_THRESHOLD] == "Campaign Ended":
            goal = row[RPT_COL_GOAL]
            total_target_spend_per_imprviews = float(str(row[RPT_COL_TOTAL_TARGET_SPEND_PER_IMPRVIEWS]).replace(',', ''))

            if goal == "CPM":
                impressions = float(str(row[RPT_COL_TOTAL_IMPRESSIONS]).replace(',', ''))
                ratio = impressions / total_target_spend_per_imprviews
                if ratio < 0.97:
                    return "Underdelivery"
                elif ratio > 1.15 or (impressions - total_target_spend_per_imprviews > 50000):
                    return "Overdelivery"
                elif 0.97 <= ratio <= 1.15:
                    return "On Target"
            elif goal == "CPV":
                views = float(str(row[RPT_COL_TOTAL_VIEWS]).replace(',', ''))
                ratio = views / total_target_spend_per_imprviews
                if ratio < 1.00:
                    return "Underdelivery"
                elif ratio > 1.03 or (views - total_target_spend_per_imprviews > 50000):
                    return "Overdelivery"
                elif 1.00 <= ratio <= 1.03:
                    return "On Target"
            elif goal == "MS":
                cost = float(str(row[RPT_COL_TOTAL_PUB_COST]).replace(',', ''))
                ratio = cost / total_target_spend_per_imprviews
                if ratio < 1.00:
                    return "Underdelivery"
                elif ratio > 1.03 or (cost - total_target_spend_per_imprviews > 500):  # Corrected to use `cost` instead of `views`
                    return "Overdelivery"
                elif 1.00 <= ratio <= 1.03:
                    return "On Target"
        else:
            return ""
    except Exception as e:
        # Return the exception for troubleshooting
        return str(e)

    return ""

# Apply the function to each row
df1_deduplicated[RPT_COL_DELIVERY_STATUS] = df1_deduplicated.apply(calculate_delivery_status, axis=1)


##Auto. Pacing Cycle Target Remaining (Spend, Impr., Views) 
##Formula: =IF(A2<>"",IF(D2="CPM",G2-T2,if(D2="ms",G2-S2,IF(D2="CPV",G2-V2))),"")
##Python
def calculate_auto_pacing_cycle_target_remaining(row):
    if row[RPT_COL_CAMPAIGN] != "":  # Checks if the campaign column is not empty
        target_impr_per_spendviews = pd.to_numeric(row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS], errors='coerce')
        if pd.isnull(target_impr_per_spendviews):
            return ""  # or some other appropriate value for your context

        if row[RPT_COL_GOAL] == "CPM":
            return target_impr_per_spendviews - row[RPT_COL_AUTO_PACING_CYCLE_IMPR]
        elif row[RPT_COL_GOAL] == "MS":
            return target_impr_per_spendviews - row[RPT_COL_AUTO_PACING_CYCLE_PUB_COST]
        elif row[RPT_COL_GOAL] == "CPV":
            return target_impr_per_spendviews - row[RPT_COL_AUTO_PACING_CYCLE_VIEWS]
        else:
            return ""
    else:
        return ""

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS] = df1_deduplicated.apply(calculate_auto_pacing_cycle_target_remaining, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_TARGET_REMAINING_SPEND_PER_IMPRVIEWS].apply(
    lambda x: f'{x:.2f}' if not pd.isna(pd.to_numeric(x, errors='coerce')) else x
)


##Pacing Cycle Daily Allocation (Spend, Impr., Views)   
##Formula: =iferror(IF(D2="MS",(G2-S2)/AB2,IF(D2="CPM",(G2-T2)/AB2,if(D2="CPV",(G2-V2)/AB2,""))))
##Python
def calculate_pacing_cycle_daily_allocation(row):
    try:
        if row[RPT_COL_GOAL] == "MS":
            remaining_target = row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS] - row[RPT_COL_AUTO_PACING_CYCLE_PUB_COST]
            return remaining_target / row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] if row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] != 0 else 0
        elif row[RPT_COL_GOAL] == "CPM":
            remaining_target = row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS] - row[RPT_COL_AUTO_PACING_CYCLE_IMPR]
            return remaining_target / row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] if row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] != 0 else 0
        elif row[RPT_COL_GOAL] == "CPV":
            remaining_target = row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS] - row[RPT_COL_AUTO_PACING_CYCLE_VIEWS]
            return remaining_target / row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] if row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING] != 0 else 0
        else:
            return 0  # Return 0 or an appropriate value for rows that do not match any campaign type conditions
    except:
        return 0  # Handles division by zero or any other calculation error gracefully

# Apply the function to each row of the DataFrame
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS] = df1_deduplicated.apply(calculate_pacing_cycle_daily_allocation, axis=1)
df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS] = df1_deduplicated[RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS].apply(
    lambda x: f'{x:.2f}' if not pd.isna(pd.to_numeric(x, errors='coerce')) else x
)


##Recommended Daily Budget
##Formula: =IFERROR(IF(AND(AA2=0,D2="ms"),AC2,IF(AND(AA2=0,D2="CPM"),(O2/P2)*AC2,IF(AND(AA2=0,D2="cpv"),O2/V2*AC2,IF(D2="MS",(G2-S2)/AB2,IF(D2="CPM",(O2/P2)*AO2,IF(D2="CPV",O2/V2*AO2,"")))))),"")
##Python
def convert_to_float(value):
    """
    Converts a value to float. If the value is a string that includes commas,
    it removes the commas before conversion. If the value is empty or not convertible,
    it returns 0.0.
    
    Parameters:
    value (str or float): The value to convert.
    
    Returns:
    float: The converted value or 0.0 if conversion is not possible.
    """
    try:
        # Check if the value is already a float
        if isinstance(value, float):
            return value
        # If the value is a string, remove commas and convert to float
        if isinstance(value, str) and value:
            return float(value.replace(',', ''))
    except ValueError:
        pass
    # Return 0.0 for empty strings or values that cannot be converted
    return 0.0
def convert_to_float(value):
    """
    Converts a value to float. If the value is a string that includes commas,
    it removes the commas before conversion. If the value is empty or not convertible,
    it returns 0.0.
    
    Parameters:
    value (str or float): The value to convert.
    
    Returns:
    float: The converted value or 0.0 if conversion is not possible.
    """
    try:
        # Check if the value is already a float
        if isinstance(value, float):
            return value
        # If the value is a string, remove commas and convert to float
        if isinstance(value, str) and value:
            return float(value.replace(',', ''))
    except ValueError:
        pass
    # Return 0.0 for empty strings or values that cannot be converted
    return 0.0
def calculate_recommended_daily_budget(row):
    """
    Calculates the recommended daily budget based on campaign goal, remaining targets, and pacing.
    
    Parameters:
    row (pd.Series): A row from the DataFrame.
    
    Returns:
    str: The recommended daily budget for the campaign as a formatted string.
    """
    try:
        # Check if the Auto. Pacing Cycle Threshold indicates the campaign has ended
        if row['Auto. Pacing Cycle Threshold'] == "Campaign Ended":
            return ""
            
        # Use the convert_to_float function for all conversions
        days_elapsed = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_DAYS_ELAPSED])
        pub_cost = convert_to_float(row[RPT_COL_TOTAL_PUB_COST])
        total_impressions = convert_to_float(row[RPT_COL_TOTAL_IMPRESSIONS])
        total_views = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_VIEWS])
        daily_target = convert_to_float(row[RPT_COL_AUTO_PACING_DAILY_TARGET_SPEND_PER_IMPRESSIONSVIEWS])
        goal = row[RPT_COL_GOAL]
        if days_elapsed == 0 and goal == "MS":
            result = daily_target
        elif days_elapsed == 0 and goal == "CPM":
            result = (pub_cost / total_impressions) * daily_target
        elif days_elapsed == 0 and goal == "CPV":
            result = (pub_cost / total_views) * daily_target    
        elif goal == "MS":
            target = convert_to_float(row[RPT_COL_TARGET_IMPR_PER_SPENDVIEWS])
            remaining_days = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_DAYS_REMAINING])
            apc_pub_cost = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_PUB_COST])
            result = (target - apc_pub_cost) / remaining_days if remaining_days else ""
        elif goal == "CPM":
            allocation = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS])
            result = (pub_cost / total_impressions) * allocation if total_impressions else ""
        elif goal == "CPV":
            allocation = convert_to_float(row[RPT_COL_AUTO_PACING_CYCLE_DAILY_ALLOCATION_SPEND_PER_IMPRVIEWS])
            result = (pub_cost / total_views) * allocation if total_views else ""
        else:
            result = "" 

        if result <= 0:
            result = 1.00  # Set a default value if the result is less than or equal to 0

    except Exception as e:
        print(f"Error calculating recommended daily budget for campaign {row[RPT_COL_CAMPAIGN]}: {e}")
        result = ""  # Set a default value in case of an error

    # Ensure result is a float before formatting
    try:
        result = float(result)
        return f"{result:.2f}"
    except ValueError:
        # If result cannot be converted to float, return it as is
        return result
        
# Apply the adjusted function
df1_deduplicated[RPT_COL_RECOMMENDED_DAILY_BUDGET] = df1_deduplicated.apply(calculate_recommended_daily_budget, axis=1)
#df1_deduplicated[RPT_COL_RECOMMENDED_DAILY_BUDGET] = df1_deduplicated[RPT_COL_RECOMMENDED_DAILY_BUDGET].apply(
#    lambda x: f'{x:.2f}' if isinstance(x, (int, float)) and not pd.isna(x) else ""
#)
# Assuming df1_deduplicated is your final DataFrame after all transformations
print(df1_deduplicated[[RPT_COL_CAMPAIGN, RPT_COL_RECOMMENDED_DAILY_BUDGET]].head())  # Print a sample for verification
outputDf = df1_deduplicated

Post generated on 2024-05-15 07:44:05 GMT

comments powered by Disqus