No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python pytrends Line Chart Tutorial

by Khaleel O.
February 10, 2022
in Python
Reading Time: 4 mins read
A A
python pytrends tutorial
python pytrends tutorial

Let’s do a Python pytrends Tutorial! The pytrends library is the unofficial API for Google Trends. Google Trends is a research tool that is used to find out what keywords are trending in Google Search.

First we have to install it, which we can do with the following code: pip install pytrends . This library requires Python 3.3+ to work, so make sure you have a suitable version. We will be using Python 3.8.10 for this example.

Next, let’s write some code:

from pytrends.request import TrendReq
import pandas as pd

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

kw_list = ["dating"]

dating_trends_1mo  = pytrends.get_historical_interest(kw_list, year_start=2022, month_start=1, day_start=1, hour_start=0, year_end=2022, month_end=2, day_end=1, hour_end=0, cat=0, geo='US-CA', gprop='', sleep=60)

dating_trends_1mo.to_csv("dating_trends_1mo.csv")

Let’s explain what is happening here:

  1. We import the pytrends.request library and the TrendReq method. We also import the pandas library because the result of our request will be a dataframe which we will then export as a CSV file.
  2. Method TrendReq() is our pytrends request. We supply two parameters: hl with value en-US which is the host language for accessing Google Trends and tz which is the timezone offset for our current location. The timezone is important so that we get the correct time and date in our result.
  3. List kw_list is a list of our keywords for which we would like to retrieve Google Trends data. In this case we want to find out the trend for topic keyword dating.😍
  4. The pytrends.get_historical_interest() method will give us the historical hourly interest for the given keyword according to Google data as a dataframe, which we will store as dating_trends_1mo. We supply the start date time and end date time, obviously. We want data for the month of January 2022. Additionally, we supply the following parameters:
    • cat is 0 which will reference all Google Trends categories
    • geo is the location. We want to retrieve hourly interest for California, USA
    • gprop is the Google Property to use, by default this is web search
    • sleep spaces our API calls so that we aren’t rate limited
  5. We save our results to a CSV file on disk. The file will reside in the same folder as our python script.

When the above code executes, we should have a new file on disk called: dating_trends_1mo.csv. It will have hourly interest for the topic of Dating for the state of California, USA for January 2022. The “interest” is rated on the scale of 1 to 100. Rating 100 means high interest.

We can take our example a step further and produce a line chart that will give is a visual of the trend. First, make sure Plotly is installed. If not, the command is pip install plotly-express.

Here is the code:

import pandas as pd
import plotly.express as px

df = pd.read_csv('dating_trends_1mo.csv')

df['date'] = pd.to_datetime(df['date'], errors='coerce')

fig = px.line(df.groupby(df.date.dt.day).agg({'dating':'mean'}), \
                y = 'dating', \
                title='Pytrends for Keyword DATING January 2022')
fig.show()

Let’s explain what is happening here:

  1. We import our plotly library and pandas as usual.
  2. We read our previously generated CSV file from disk: dating_trends_1mo.csv
  3. We ensure that the date column is a proper date.
  4. We group the date column by day and find the average rating per day. This makes our graph cleaner.
  5. We create a line graph that shows the pytrends data visually.

When the code executes, you should see the following graph on the screen:

python pytrends tutorial
Pytrends Trend Data Visualization with Plotly

Easy right? Now we see the average day-to-day pytrends data for Jan 2022 for California, USA. Visuals are always a good idea when you are talking about any type of trend data. Below is our full code:

from pytrends.request import TrendReq

import pandas as pd
import plotly.express as px


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

kw_list = ["dating"]

dating_trends_1mo  = pytrends.get_historical_interest(kw_list, year_start=2022, month_start=1, day_start=1, hour_start=0, year_end=2022, month_end=2, day_end=1, hour_end=0, cat=0, geo='US-CA', gprop='', sleep=60)
dating_trends_1mo.to_csv("dating_trends_1mo.csv")

df = pd.read_csv('dating_trends_1mo.csv')
df['date'] = pd.to_datetime(df['date'], errors='coerce')

fig = px.line(df.groupby(df.date.dt.day).agg({'dating':'mean'}), \
                y = 'dating', \
                title='Pytrends for Keyword DATING January 2022')
fig.show()

Find pytrends on Github HERE. Thanks for reading and good luck! 👌👌👌

Tags: pytrends
Previous Post

Python regex for IP Address

Next Post

How to Download Instagram Reels in Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy