Script 573: Campaign Budget Dimension Updates

Purpose

Python script to update campaign information based on specified conditions.

To Elaborate

The Python script updates campaign information in a DataFrame based on specified conditions. It filters rows in the DataFrame based on the target campaign name and campaign type, and then updates the values of certain columns for the matching campaigns.

Walking Through the Code

  1. The script defines a function update_campaign_info that takes an input DataFrame, campaign type, and target campaign name as parameters.
  2. The function filters rows in the input DataFrame where the campaign matches the target campaign for the specified type.
  3. An empty DataFrame output_df is initialized to store the results.
  4. The function iterates through each row in the target campaign DataFrame.
  5. Depending on the campaign type, the function defines conditions to match other campaigns or performance max campaigns.
  6. The function applies the conditions to the input DataFrame and retrieves the matching campaigns.
  7. If there are matching campaigns, the function retrieves values from the row and updates the corresponding columns in the matching campaigns using .loc.
  8. The updated matching campaigns are concatenated to the output DataFrame.
  9. The function returns the output DataFrame.
  10. The script defines the input DataFrame and output columns.
  11. Target campaign names are specified for each campaign type.
  12. The function update_campaign_info is called for search, shopping, and performance max campaigns, and the results are stored in separate output DataFrames.
  13. The output DataFrames are concatenated into one final output DataFrame outputDf.

Vitals

  • Script ID : 573
  • Client ID / Customer ID: 1306926667 / 60270093
  • Action Type: Bulk Upload (Preview)
  • Item Changed: Campaign
  • Output Columns: Account, Campaign, Budget Start Date, Budget End Date, Pacing - Campaign Budget
  • Linked Datasource: M1 Report
  • Reference Datasource: None
  • Owner: Chris Jetton (cjetton@marinsoftware.com)
  • Created by Chris Jetton on 2023-12-07 20:45
  • Last Updated by Chris Jetton on 2023-12-11 20:08
> 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
##
## name: Campaign Budget Dimension Updates
## description:
##  
## 
## author: 
## created: 2023-12-07
## 

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

# Function to update campaign information
def update_campaign_info(input_df, campaign_type, target_campaign_name):
    # Filter rows where the Campaign matches the target campaign for the specified type
    target_campaign = input_df[input_df["Campaign"] == target_campaign_name]

    print(f"Number of target_campaigns ({campaign_type}): {len(target_campaign)}")

    # Initialize an empty DataFrame to store the results
    output_df = pd.DataFrame(columns=input_df.columns)

    # Iterate through each row in the target_campaign DataFrame
    for _, row in target_campaign.iterrows():
        # Define the conditions based on campaign type
        if campaign_type == "Performance Max":
            conditions = (
                (input_df["Campaign"].str.contains('PMax', case=False, regex=True)) &
                (~input_df["Campaign"].str.contains('Vendor', case=False, regex=True)) &
                (input_df["Campaign Type"] == "Performance Max") &
                (input_df["Campaign Status"] == "Active") &
                (input_df["Account"] == row["Account"]) &
                (input_df["AVB ID"] == row["AVB ID"])
            )   
        else: 
        # Define the conditions to match other campaigns
            conditions = (
                (input_df["Campaign"].str.contains(row['Campaign'])) &
                (input_df["Campaign Type"] == campaign_type) &
                (input_df["Campaign Status"] == "Active") &
                (input_df["Account"] == row["Account"]) & 
                (input_df["AVB ID"] == row["AVB ID"])
            )

        # Apply conditions and copy values to the output DataFrame
        matching_campaigns = input_df[conditions]

        print(f'Original campaign ({campaign_type}): {row["Campaign"]}')
        print('matching campaigns: ', matching_campaigns["Campaign"].tolist())
        print(f"Number of matching_campaigns: {len(matching_campaigns)}")

        if not matching_campaigns.empty:
            # Retrieve values from the row
            budget_start_date = pd.to_datetime(row[BULK_COL_BUDGET_START_DATE], format='%Y/%m/%d').strftime('%m/%d/%y')
            budget_end_date = pd.to_datetime(row[BULK_COL_BUDGET_END_DATE], format='%Y/%m/%d').strftime('%m/%d/%y')

            pacing_campaign_budget = row[BULK_COL_PACING_CAMPAIGN_BUDGET]
            print('budget start date')
            print(budget_start_date)
            print('budget end date')
            print(budget_end_date)
            print('pacing_campaign_budget')
            print(pacing_campaign_budget)

            # Make a copy to avoid SettingWithCopyWarning
            matching_campaigns = matching_campaigns.copy()

            # Update values in the output DataFrame using .loc
            matching_campaigns.loc[:, BULK_COL_BUDGET_START_DATE] = budget_start_date
            matching_campaigns.loc[:, BULK_COL_BUDGET_END_DATE] = budget_end_date
            matching_campaigns.loc[:, BULK_COL_PACING_CAMPAIGN_BUDGET] = pacing_campaign_budget

            # Concatenate the updated matching campaigns to the output DataFrame
            output_df = pd.concat([output_df, matching_campaigns], ignore_index=True)
            print('output dataframe')
            print(output_df)

    return output_df

# Primary data source and columns
input_df = dataSourceDict["1"]

# Output columns and initial values
RPT_COL_ACCOUNT = 'Account'
RPT_COL_CAMPAIGN = 'Campaign'
RPT_COL_CAMPAIGN_TYPE = 'Campaign Type'
RPT_COL_CAMPAIGN_STATUS = 'Campaign Status'
RPT_COL_AVB_ID = 'AVB ID'
RPT_COL_BUDGET_START_DATE = 'Budget Start Date'
RPT_COL_BUDGET_END_DATE = 'Budget End Date'
RPT_COL_PACING_CAMPAIGN_BUDGET = 'Pacing - Campaign Budget'
BULK_COL_BUDGET_START_DATE = 'Budget Start Date'
BULK_COL_BUDGET_END_DATE = 'Budget End Date'
BULK_COL_PACING_CAMPAIGN_BUDGET = 'Pacing - Campaign Budget'

# Specify target campaign names for each type
search_target_campaign_name = "SE : Custom :: Appliances"
shopping_target_campaign_name = "SH : Custom :: Appliances"
performance_max_target_campaign_name = "PMax: Test"

# Update information for Search campaigns
output_df_search = update_campaign_info(input_df, "Search", search_target_campaign_name)

# Update information for Shopping campaigns
output_df_shopping = update_campaign_info(input_df, "Shopping", shopping_target_campaign_name)

# Update information for Performance Max campaigns
output_df_performance_max = update_campaign_info(input_df, "Performance Max", performance_max_target_campaign_name)

# Combine the results into one output DataFrame
outputDf = pd.concat([output_df_search, output_df_shopping, output_df_performance_max], ignore_index=True)

# You can now use combined_output_df as the final report

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

comments powered by Disqus