Pytrends in Python: How to Use Google Trends API for Data Analysis

pytrends in python

Introduction

Google Trends is a powerful tool for analyzing search trends over time. However, manually checking trends can be time-consuming. This is where Pytrends in Python comes in. Pytrends is an unofficial API that allows you to fetch Google Trends data programmatically.

In this article, we will explore how to use Pytrends with multiple examples to analyze search trends effectively.

Read also: What is Seaborn in Python? A Guide to Data Visualization

What is Pytrends?

Pytrends is a Python library that interacts with Google Trends and allows users to retrieve search interest data for specific keywords. It helps track keyword popularity, compare multiple terms, and analyze trends by region or category.

Installation

Install Pytrends using the following command:

pip install pytrends

Intialize Pytrends API

First, import the necessary module and initialize the Pytrends API:

from pytrends.request import TrendReq

# Create a Pytrends request
pytrends = TrendReq(hl='en-US', tz=360)

Checking Interest Over Time

The function interest_over_time() in Pytrends retrieves the search interest data for specified keywords over a given time period.

How It Works

It fetches the relative search interest for each keyword over time. The values range from 0 to 100, where:

  • 100 represents peak search interest.
  • 50 means the search term is half as popular as at its peak.
  • 0 means insufficient data for that time period.

The function returns a Pandas DataFrame, where:

  • The index represents time (usually daily or weekly).
  • Each column represents a keyword.
  • An additional ā€˜isPartialā€™ column indicates whether the data is partial.
# Define keyword(s)
kw_list = ["Python", "Java"]

# Build payload
pytrends.build_payload(kw_list, timeframe='today 12-m')

# Get interest over time
data = pytrends.interest_over_time()
print(data.head())

Output

            Python  Java  isPartial
date                               
2024-01-28      95    61      False
2024-02-04      97    60      False
2024-02-11     100    66      False
2024-02-18      97    64      False
2024-02-25      96    63      False

Interest by Region

Regional interest can provide us valuable insights into the geographic popularity of a keyword. For example, if youā€™re searching the popularity of the Python programming language, understanding which regions are most interested in it can guide us targeted marketing strategies or content creation.

Hereā€™s an example that shows how to retrieve the regional interest for the keyword ā€œPythonā€ and filter it by the top regions:

# Fetch interest by region for the keyword "Python"
pytrends.build_payload(["Python"], timeframe='today 12-m', geo='')
data = pytrends.interest_by_region()

# Sort the data to show the top 10 regions with the highest interest in Python
top_regions = data.sort_values(by="Python", ascending=False).head(10)

# Display the top 10 regions
print("Top 10 Regions Interested in Python:")
print(top_regions[['Python']])

Output

Top 10 Regions Interested in Python:
             Python
geoName            
China           100
Singapore        23
Israel           21
Hong Kong        18
India            16
Switzerland      15
South Korea      14
Tunisia          13
Taiwan           12
Russia           12

Key Details:

  • geo parameter: This can be used to specify a region or country. For example, geo='US' would fetch data for the entire United States, or geo='IN' for India.
  • timeframe parameter: Defines the period over which the data is collected, like today 12-m for the last 12 months or now 7-d for the past week.

Related Queries

The related_queries() function in Pytrends retrieves related search queries to a specific keyword. This function provides valuable insights into what other topics or queries are being searched in relation to the keyword youā€™re analyzing. It categorizes the results into top queries and rising queries:

  • Top related queries: These are the most popular related searches in the given timeframe.
  • Rising related queries: These are searches that have seen the most significant increase in interest over a recent period, indicating trending topics.
# Create a Pytrends request
from pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=360)

# Specify the keyword
keyword = ['Google', 'Facebook']

# Build the request payload
pytrends.build_payload(kw_list=keyword)


try:
    # Retrieve related queries data with error handling
    related_queries = pytrends.related_queries()

    top_queries = related_queries[keyword].get('top')
    rising_queries = related_queries[keyword].get('rising')

    print("Top Related Queries:")
    print(top_queries.head() if top_queries is not None else "No data available")

    print("\nRising Related Queries:")
    print(rising_queries.head() if rising_queries is not None else "No data available")
except (KeyError, IndexError):
    print("No related queries found for", keyword)

Output

No related queries found for ['Google', 'Facebook']

Retrieving Google Autocomplete Suggestions

Google Autocomplete provides search predictions based on what users commonly search for. With Pytrends, you can fetch these suggestions programmatically to understand what people are looking for related to a specific keyword. This is useful for SEO, content creation, and keyword research.

suggestions = pytrends.suggestions(keyword="Python")

# Display suggestions
for suggestion in suggestions:
    print(suggestion['title'], ":", suggestion['type'])

Output

Python : Programming language
Ishan Sharma : YouTuber
Python family : Snake
Python for Data Analysis: Data Wrangling with Pandas, NumPy, and Jupyter : Book by Wes McKinney
Python : Snake

Fetching Daily Trending Searches

Apart from analyzing specific keywords, Pytrends also allows us to fetch Googleā€™s daily trending searches using the today_searches() function. This helps in identifying whatā€™s currently trending worldwide or in a specific country.

from pytrends.request import TrendReq
import re

# Create a Pytrends request
pytrends = TrendReq(hl='en-US', tz=360)

# Get today's trending searches
trending_searches = pytrends.today_searches()

# Extract search terms from URLs
def extract_search_term(url):
    match = re.search(r"q=([^&]+)", url)
    return match.group(1).replace("+", " ") if match else url

# Convert to a readable list
trending_topics = [extract_search_term(link) for link in trending_searches]

# Print the cleaned trending searches
print("Today's Trending Searches in India:")
for i, topic in enumerate(trending_topics, start=1):
    print(f"{i}. {topic}")

Output

Today's Trending Searches:
1. Benavidez vs Morrell
2. UNC vs Duke
3. Espanyol vs Real Madrid
4. Ken Martin
5. Celtics
6. Warriors
7. Senior Bowl 2025
8. Kestrel
9. NASCAR
10. Tennessee basketball
11. Bournemouth vs Liverpool
12. Lakers vs Knicks
13. Jey Uso
14. Pebble Beach
15. Serie del Caribe 2025
16. Twinless
17. Nuggets vs Hornets
18. Somalia

Fetching Trends for a Specific Country

You can also get country-specific trending searches by passing a country code to today_searches(). For example, to fetch trending searches in India (ā€˜INā€™):

trending_searches_india = pytrends.today_searches(pn='IN')
print(trending_searches_india.head())

Limitations of Using Pytrends Library

While Pytrends is a powerful tool, it has some limitations:

  • Unofficial API: Pytrends is not an official Google API, so it may break if Google changes its trends service.
  • Rate Limiting: Google may block excessive requests if too many are sent in a short period.
  • Data Sampling: The data provided by Google Trends is not raw search volume but a normalized value, making precise numerical analysis difficult.
  • Limited Historical Data: Some historical data is not available for specific queries.
  • Geo-Specific Restrictions: Certain queries may not be available in all countries or regions.

Read also: Google Colab for Python: Advantages vs Disadvantages

Summary

Do you want to analyze Google Trends data for SEO or market research? Pytrends is a Python library that allows you easily extract valuable insights, from keyword popularity to related search queries. This tutorial provides practical examples to get you started with Pytrends in your projects.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194