Track Your Fitness with Python: Analyzing Google Fit Data

Google Fit is a powerful tool for tracking your physical activity and health metrics over time. Using the sensors in your phone or wearable device, Google Fit continuously collects data on your steps taken, distance traveled, calories burned, heart rate, and more.

But have you ever wanted to dig deeper into that treasure trove of personal fitness data? By exporting your Google Fit history and analyzing it with Python, you can unlock fascinating insights about your health and activity patterns over days, weeks, months and years.

In this step-by-step guide, I‘ll show you exactly how to download your Google Fit data, load it into Python, prepare it for analysis, and create interesting visualizations. No prior experience with Python or data analysis is required. Let‘s jump in!

Downloading Your Google Fit Data

The first step is to export your fitness tracking data from Google. Fortunately, Google makes it easy to download a copy of your data from any of its products, including Google Fit, using a tool called Google Takeout. Here‘s how:

  1. Go to takeout.google.com and make sure you are signed in with the Google account whose data you want to export.

  2. Click "Deselect all" as we only want Google Fit data. Scroll down to find the "Fit" option and check the box next to it.

  3. Leave the export settings at default or customize them if desired. You can choose the file type and size for the archive. For this tutorial, the default of a zip file with 2GB size limit is fine.

  4. Click "Next step", review your order, and then click "Create export". Google will start generating your archive.

  5. Once your Google Fit archive is created (which may take a few minutes), you‘ll receive an email notification with a download link. Download the zip file and extract its contents to a folder on your computer.

Your exported Google Fit data will include several CSV files containing daily, monthly, and yearly metrics, as well as raw session data, step counts, and other activity records. For this analysis, we‘ll focus on the high-level daily aggregated metrics found in the "Daily Aggregations.csv" file.

Screenshot of Google Fit exported data files

Preparing the Fitness Data for Analysis

Now that you have your Google Fit data exported, let‘s load it into Python and get it ready for analysis. We‘ll be using the popular pandas library to work with the data as a dataframe.

First, make sure you have Python and the pandas library installed. You can install pandas with pip:

pip install pandas 

Next, read in the "Daily Aggregations.csv" file using pandas‘ read_csv function:

import pandas as pd

df = pd.read_csv(‘Daily Aggregations.csv‘, parse_dates=[‘Date‘], index_col=‘Date‘) 

We set the "Date" column as the dataframe index and parse the dates to make it easier to work with later on.

Let‘s take a look at the loaded data:

print(df.head())
print(df.info())

This outputs the first few rows of the dataframe as well as summary information on each column, including the data type and number of non-null values.

The daily aggregated data contains columns for each day‘s total step count, distance traveled, calories expended, move minutes, and more. Some metrics may have many missing values depending on which sensors your device has and which types of workouts you tracked.

To prepare the data for analysis, we‘ll:

  1. Remove any unnecessary columns
  2. Handle missing values
  3. Add additional date-related fields

First, let‘s remove the columns we don‘t need for our analysis. For example, the "Segment.X" columns contain detailed intraday data that we likely won‘t use:

cols_to_drop = [c for c in df.columns if ‘Segment‘ in c]
df = df.drop(columns=cols_to_drop)

Next, decide how to deal with missing (NaN) values in the data. We can either remove any rows with missing data or fill in the missing values (e.g. with zero). For simplicity, let‘s remove rows with missing step counts:

df = df.dropna(subset=[‘Step Count‘])

Finally, let‘s add some additional date-related fields that will come in handy for grouping and aggregating the data later on:

df[‘Day of Week‘] = df.index.day_name()
df[‘Month‘] = df.index.strftime(‘%b‘)
df[‘Year‘] = df.index.year

We now have a clean daily Google Fit summary dataframe ready for exploration and visualization!

Analyzing the Google Fit Data

With our data loaded and prepared, we can start to uncover interesting insights about our fitness habits and patterns. We‘ll compute some summary statistics and create a few charts to visualize trends and distributions in the key fitness metrics.

Summary Statistics

How many days of Google Fit data do we have?

print(len(df))
# 892 days

What is the average number of steps, distance, and calories per day?

print(df[[‘Step Count‘,‘Distance‘,‘Calories Expended‘]].mean())
Step Count           7164.24
Distance              5.79
Calories Expended    2688.11

What were the highest and lowest step counts?

print(df[‘Step Count‘].max())  
# 26358
print(df[‘Step Count‘].min())
# 508

We can start to get a sense of our typical activity level, the total amount of historical data, and the range in daily steps and other metrics.

Data Visualization

Let‘s create a few charts to better understand patterns in the data:

1. Daily steps over time

First, let‘s visualize our daily step counts over the full history to look for any long-term trends or patterns:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(15,5))
ax.plot(df.index, df[‘Step Count‘])
ax.set(title=‘Daily Steps Over Time‘, 
       xlabel=‘Date‘,
       ylabel=‘Number of Steps‘)
plt.show()

Line chart of daily step counts over time

Are there any noticeable changes in your step counts from earlier to more recent years? Do you see weekly or seasonal fluctuations in the chart?

2. Average steps by day of week

Next, let‘s compare our typical activity level (in terms of steps) on each day of the week:

import seaborn as sns

fig, ax = plt.subplots(figsize=(10,5))
sns.barplot(data=df, x=‘Day of Week‘, y=‘Step Count‘, 
            order=[‘Monday‘,‘Tuesday‘,‘Wednesday‘,‘Thursday‘,‘Friday‘,‘Saturday‘, ‘Sunday‘],
            ci=None)
plt.xticks(rotation=45)
ax.set(title=‘Average Steps by Day of Week‘, ylabel=‘Average Number of Steps‘)
plt.show()

Bar chart comparing average step counts by day of week

Are you more or less active on weekends compared to weekdays? This could reflect differences in your work and exercise routines.

3. Activity breakdown by hour of day

When are you most active during the day? Let‘s visualize steps taken by hour in a heatmap:

df[‘Hour‘] = df.index.hour

hourly_avg_steps = df.groupby([‘Day of Week‘,‘Hour‘])[‘Step Count‘].mean().unstack(level=0)

fig, ax = plt.subplots(figsize=(10,8)) 
sns.heatmap(hourly_avg_steps, cmap=‘viridis‘)
plt.yticks(range(0,24))
ax.set(title=‘Average Steps by Time of Day and Day of Week‘, 
       xlabel=‘Day of Week‘,
       ylabel=‘Hour of Day‘)
plt.show()

Heatmap showing average step counts by hour and day of week

This heatmap makes it easy to spot patterns in when you tend to be most active each day. We can see weekdays and weekends have quite different activity patterns, with more steps earlier on weekdays and more in the middle of the day on weekends.

4. Daily steps vs. move minutes

Finally, let‘s explore the relationship between two activity metrics tracked by Google Fit – steps and "move minutes".

Move minutes are intended to capture your total active time each day, including lower-intensity activities not counted as steps. We would expect them to be positively correlated with step count, but there may be interesting outliers or patterns.

fig, ax = plt.subplots(figsize=(10,6))
sns.scatterplot(data=df, x=‘Step Count‘, y=‘Move Minutes‘)
ax.set(title=‘Daily Steps vs. Move Minutes‘, 
       xlabel=‘Number of Steps‘,
       ylabel=‘Move Minutes‘)
plt.show()  

Scatterplot showing relationship between daily steps and move minutes

As expected, we see a strong positive relationship between steps and move minutes. But there are some interesting data points like days with very high numbers of steps but low active minutes, which may indicate lots of short walks or jogs. Days with high move minutes but low step counts likely reflect activities like swimming, biking, weight lifting, etc.

With this framework, you can conduct many more analyses and create other interesting visualizations of your own Google Fit data over time. Mining your personal fitness data may uncover surprising insights about your exercise and activity habits that you can use to make positive changes in your routines.

Conclusion

In this article, I demonstrated how you can access, prepare, and analyze your own fitness tracking data collected from Google Fit. By exporting your data, loading it into Python, cleaning it up a bit, and utilizing libraries like pandas, matplotlib and seaborn, you can start discovering fascinating patterns and insights in your physical activity over time.

Some key steps we covered:

  • Exported Google Fit daily activity data using Google Takeout
  • Loaded the CSV data into a pandas dataframe and cleaned it up
  • Added additional datetime-based columns to enable grouping and aggregating
  • Calculated high-level descriptive statistics on steps, distance, calories, etc.
  • Visualized activity metrics over time, by day of week, by hour, and compared to each other

I encourage you to dig into your own data and uncover unique and interesting trends. Consider other types of visualizations to create, like seasonal plots, cumulative metrics over time, or faceted charts comparing multiple metrics. Think about what other data you could join with your Google Fit history to enable deeper analysis, like weather, location, calendar events, etc.

I hope this guide inspires you to start exploring and finding meaning in your own self-tracking data. By understanding your historical patterns, you can make more informed decisions about how to improve your fitness, health and wellbeing. The data is there – now it‘s up to you to unlock its secrets!

Here are some additional resources you may find helpful:

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts