Python For Google Ads: 3 Copy-Paste Examples

Python For Google Ads: 3 Copy-Paste Examples

Think you need to be a computer engineer or data scientist to use code for data analysis? Think again.

Let me show you just how easy it can be to use Python for analyzing and working with data. ??


?? First things first, if you don't have anything to run Python code with, you'll need to download something to do so. I recommend downloading Anaconda - it's free!

?? I've provided the steps below in a form that's best suited for use within Jupyter Notebook, which is included with Anaconda. But the code is essentially the same for use in other applications that can run Python code.

?? Lots of YouTube videos and articles out there on setting up and using these tools - it's pretty simple, don't worry. ???


?? My hope is that if you've avoided using Google Ads Scripts or Python because it looks too intimidating, this guide will give you a simple look at how accessible this skillset is for those willing to put in a little extra up-front effort.

Believe me, once you start conducting data analysis with code and you see just how fast and effective it is, you'll never want to try to do the same things in a spreadsheet or in the interface again ??

Let's get started!


Preparing Customer Lists For Upload

1?? Context: You have a customer list you'd like to upload to Google Ads

2?? Access Python (e.g. via Jupyter Notebook, VSCode, Spyder, Anaconda Prompt) & import the Pandas library:

import pandas as pd
pd.set_option('display.max_columns', 100)        

3?? Get the customer list into Python:

df = pd.read_csv(r'\customer-lists\customer_list.csv')        

4?? Review column headers:

df.head()        
No alt text provided for this image

5?? (If necessary) Remove unnecessary column(s):

df = df.drop(columns = ['unnecessary_column1', 'unnecessary_column2'])        

6?? (If columns removed in previous step) Confirm change(s):

df.head()        
No alt text provided for this image

7?? (If necessary) Edit column names & confirm changes:

df.columns = ['Email','First name', 'Last name', 'Zip', 'Phone']
df.head()        
No alt text provided for this image

8?? (If necessary & appropriate) Add country column:

df.insert(5, 'Country', 'us')        

9?? (If column added in previous step) Confirm change:

df.head()        

?? Create new csv for upload:

df.to_csv(r'customer-lists/master_customer_list-last_540_days-product_type_A-v2023_04_12.csv', index=False)        
No alt text provided for this image


?? Note the "r" before '(csv file name)' in step 3 and 10 is only needed for Windows users who have "\" in their file paths.

And yes, if feasible, ideally you would automate email/customer list updates via something like Zapier ??

Obviously, you could do this in Excel or (eesh..) Google Sheets ??, but for larger files - let's say >1M rows, you're definitely better off using Python for this.

?? Here's the full code:

# Import libraries
import pandas as pd

# Optional: Set max columns display limit to 100
pd.set_option('display.max_columns', 100)

# Read csv - update csv file path
df = pd.read_csv(r'\customer-lists\customer_list.csv')

# Review headers
df.head()

# Optional: Remove columns - update column names
df = df.drop(columns = ['unnecessary_column1', 'unnecessary_column2'])

# Optional: Confirm headers
df.head()

# Optional: Edit headers
df.columns = ['Email', 'First name', 'Last name', 'Zip', 'Phone']

# Optional: Insert column
df.insert(5, 'Country', 'us')

# Optional: Confirm new column
df.head()

# Create new csv - update csv file path
df.to_csv(r'customer-lists/master_customer_list-last_540_days-product_type_A-v2023_04_12.csv', index=False)s        


Ad Hoc Analysis Of Large Datasets - With GroupBy

1?? Quick analysis needed: Average Days To Conversion for non-branded Search Campaigns over the last 28 days

2?? (Assuming you don't have a Google Ads API key) Download necessary data as a csv

3?? Access Python & import libraries:

import pandas as pd
import seaborn as sns        

4?? Get the file into Python:

df = pd.read_csv(r'\campaigns\all_nonbranded_search_campaigns-last_28_days-v2023_04_12.csv', header=2)        
No alt text provided for this image

5?? Group Conversions by Days To Conversion sorted by Conversions descending:

days_to_conv = df.groupby("Days to conversion")['Conversions'].sum()
days_to_conv = days_to_conv.sort_values(ascending=False)        

6?? Review:

days_to_conv        
No alt text provided for this image

7?? Let's take this one step further by visualizing this with a multi-colored horizontal bar chart:

sns.barplot(x=days_to_conv.values, y=days_to_conv.index)        
No alt text provided for this image

8?? Optional: Let's make this even more useful by adding data labels:?

days_to_conv = df.groupby("Days to conversion")['Conversions'].sum()
days_to_conv = days_to_conv.sort_values()
ax = sns.barplot(x=days_to_conv.values, y=days_to_conv.index)
ax.set_xlim([0, max(days_to_conv.values) + 20])
ax.set_ylim([-.5, len(days_to_conv) + .05])
for i in range(len(days_to_conv)):
? ? ax.text(days_to_conv.values[i] + 1, i, round(days_to_conv.values[i], 2), color='black', ha="left")        
No alt text provided for this image

Now, you could do this inside the Google Ads interface by adding a "Days To Conversion" segment to the Campaigns table, scrolling all the way down, expanding the "Search campaigns" dropdown row and analyzing from there, but with larger accounts (or even smaller ones sometimes), the load times can be awful.

Instead, you could download this report from the Reports section of Google Ads (or even schedule it to be emailed to you on a regular basis), open a Python terminal, copy-paste the code above and customize it to your needs in just a minute or two.

?? Here's the full code:

# Import libraries

import pandas as pd
import seaborn as sns

# Read csv - update csv file path
df = pd.read_csv(r'\campaigns\all-nonbranded-search-campaigns-v2023_04_12.csv', header=2)

# Review headers
df.head()

# Group conv by days to conv, sort conv desc
days_to_conv = df.groupby("Days to conversion")['Conversions'].sum()
days_to_conv = days_to_conv.sort_values(ascending=False)

# Review
days_to_conv

# Print clustered bar chart
sns.barplot(x=days_to_conv.values, y=days_to_conv.index)

# Optional: Add data labels to bar chart - replace last four lines of code with...
days_to_conv = df.groupby("Days to conversion")['Conversions'].sum()
days_to_conv = days_to_conv.sort_values()
ax = sns.barplot(x=days_to_conv.values, y=days_to_conv.index)
ax.set_xlim([0, max(days_to_conv.values) + 20])
ax.set_ylim([-.5, len(days_to_conv) + .05])
for i in range(len(days_to_conv)):
? ? ax.text(days_to_conv.values[i] + 1, i, round(days_to_conv.values[i], 2), color='black', ha="left")        


Ad Hoc Analysis Of Large Datasets - With Pivot_Table

1?? Quick analysis needed: non-branded Search Terms with >=30 Impressions last month

2?? (Assuming you don't have a Google Ads API key) Download necessary data as a csv

3?? Access Python & import libraries:

import pandas as pd
import seaborn as sns        

4?? Get the file into Python:

df = pd.read_csv(r'\search-terms\all_nonbranded_search_terms-last_month-v2023_04_12.csv')        
No alt text provided for this image

5?? Review:

df.head()        

6?? Optional: Filter out Search Terms with Added/Excluded value of "Excluded" & verify the filter worked:

df = df[df['Added/Excluded'] != 'Excluded']
unique_values = df['Added/Excluded'].unique()
unique_values        
No alt text provided for this image

7??Create a pivot table of Search Terms sorted by Cost descending:

search_terms = df.pivot_table(index="Search term", values=["Clicks", "Impr.", "Cost", "Conversions"], aggfunc="sum").sort_values(by="Cost", ascending=False)        
No alt text provided for this image

8?? Optional: Filter out Search Terms with fewer than 30 Impressions:

search_terms = search_terms[search_terms["Impr."] >= 30]        

9?? Review:

search_terms        

?? Optional: Create a new csv with the output:

search_terms.to_csv(r'\search-terms\all_nonbranded_search_terms-last_month-30_plus_imp_pivot-v2023_04_12.csv', index=True)        
No alt text provided for this image

?? Here's the full code:

# Import libraries
import pandas as pd
import seaborn as sns

# Read csv - update csv file path
df = pd.read_csv(r'\search-terms\all_nonbranded_search_terms-last_month-v2023_04_12.csv')

# Review headers
df.head()

# Optional: Filter out Excluded search terms and verify change
df = df[df['Added/Excluded'] != 'Excluded']
unique_values = df['Added/Excluded'].unique()
unique_values

# Create pivot table of search terms, sort cost desc
search_terms = df.pivot_table(index="Search term", values=["Clicks", "Impr.", "Cost", "Conversions"], aggfunc="sum").sort_values(by="Cost", ascending=False)

# Filter out <30 imp search terms
search_terms = search_terms[search_terms["Impr."] >= 30]

# Print search terms output
search_terms

# Create new csv - update csv file path
search_terms.to_csv(r'\search-terms\all_nonbranded_search_terms-last_month-30_plus_imp_pivot-v2023_04_12.csv', index=True)        


?? Ideally, you'd be utilizing the Google Ads API to get the data for these data transformations and analysis rather than downloading files and then reading them with Python. Or, second best, but not free, is to use an ETL tool like Supermetrics or Dataslayer.ai . Thing is, not everyone is willing or able to get an API key from Google, and not everyone has the desire or ability to pay for an ETL tool, so downloading files from the interface is a workable alternative.?

?? We're just scratching the surface of what's possible with Python for Google Ads in this article. For example, Python can allow you to make predictions and recommendations based on an internally-trained ML model (i.e. using your own data). Just imagine the power of a machine learning model that's been trained on your internal data and provides you with PPC recommendations that are customized for your goals and needs. ??

The possibilites are endless!

Do you use Python for data analysis? What are some ways you use Python for marketing? Share your insights in the comments! ??

___________________________

#AdvertisingAndMarketing #OnlineAdvertising #DigitalAdvertising #MarketingAndAdvertising #GoogleAdwords #PPC #GoogleAds #SEM #PaidSearch #SEA #PPCChat #DigitalMarketing #Marketing #MarketingDigital #OnlineMarketing #Analytics #Data #DataAnalysis #GoogleAnalytics #BusinessAnalytics #Analysis #MarketingAnalytics #DataAnalytics #Python

Gerd Tittel-Feller

Google Ads Consultant | Helping eCommerce Shops Make More Profit With Google Ads ??

1 年

You can use your sales transaction data from your shop provider (Shopify, WooCommerce, etc.) and create segments like VIPs (90th percentile of top spenders), Most loyal shoppers (buying most often but not spending as much), High potentials, One-Time Buyer, New Customer and much more. Then you have customer lists to upload to Google, which you can treat entirely differently depending on what segment they belong to. Or you can tag them in an email software like Klaviyo and create different flows for them. Also thanks to ChatGPT and Co you can generate the necessary code fast, only needing a basic understanding of Python.

Emilio Sotos

Data-Driven Marketing ?? Data Analyst | Excel | SQL | Power BI

1 年

Brilliant stuff. I think Python could be a good add on for every PPC manager.

要查看或添加评论,请登录

Cory Lindholm ?? ???????? ???????????? ????????????的更多文章

社区洞察

其他会员也浏览了