Copied to clipboard






Google Colab · GitHub · pandas · CSV

How to Import Dataset
from GitHub to Colab

You can import a dataset from GitHub to Google Colab without downloading the file to your computer. If your dataset is a publicly accessible CSV file, the easiest method is to copy its Raw GitHub URL and load it directly using Python’s pandas library.

For example, you can load a CSV file into Google Colab with just three lines of Python — pandas reads the file directly from GitHub and displays the first five rows. You do not need to install Git, clone a repository, or manually download the CSV. In this tutorial, you will learn how to get a raw GitHub URL, load CSV files with pandas, download datasets into Colab, import multiple datasets, work with other file formats, and fix common errors.

Jump to the 5-step method
5Step method
6Common fixes
9FAQ answers
50+Code snippets
Before you start

What do you need before importing a dataset from GitHub?

Before loading a dataset, it helps to understand the tools and file types involved.

What is Google Colab?

Google Colab is an online Python notebook environment that allows you to write and execute Python code directly in your browser. It is commonly used for data analysis, machine learning, deep learning, and educational projects.

You do not need to install Python on your computer to start using Colab.

You can create a new notebook at Google Colab.

What is GitHub?

GitHub is a platform where developers share, manage, and store code, files, and projects.

Many students, researchers, and developers use GitHub to share datasets alongside their Python projects. You can access publicly available files through a web browser or directly from Python.

What is a dataset?

A dataset is a collection of information organized for analysis. It may contain records about flowers, students, customers, products, weather, financial transactions, or other subjects.

For example, a dataset containing students’ exam scores might include columns for student names, study hours, attendance, and grades.

What is a CSV file?

CSV stands for Comma-Separated Values.

A CSV file stores tabular data in plain text. Each row represents a record, and values are usually separated by commas.

Example:

sample.csv
name,age,score
Alice,20,85
Bob,21,92
Charlie,19,78

CSV files are popular in data science because they can be read by Python, spreadsheets, database tools, and many other applications.

Why use pandas to import datasets?

Pandas is a Python library designed for working with structured data.

Its read_csv() function allows you to read CSV files into a DataFrame, which is a table-like data structure that makes it easy to explore, clean, filter, and analyze data.

Pandas is particularly useful in Google Colab because it allows you to load a publicly accessible CSV file directly from a URL.

The core method

How to import a dataset from GitHub to Colab using pandas

You can import a CSV dataset from GitHub directly into Google Colab using pandas.read_csv().

This method works for publicly accessible CSV files that pandas can retrieve through their raw URLs.

In this example, we will use the Iris dataset, which contains measurements of flowers and their species. It is frequently used in introductory machine learning exercises.

Example dataset URL:

iris_url.txt
https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv

Step 1: Open Google Colab

  1. Visit Google Colab.
  2. Create a new notebook.
  3. Click an empty code cell.
  4. Copy the following code into the cell.

Step 2: Import pandas and load the dataset

import_pandas.py
import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

df = pd.read_csv(url)

df.head()

Run the cell by clicking the play icon or pressing Shift + Enter.

The first five rows of the dataset should appear below your code.

How does this code work?

1. Import pandas

import_only.py
import pandas as pd

This imports the pandas library into Python.

The pd alias is a commonly used abbreviation for pandas. It makes pandas functions easier to access without typing the full library name.

2. Define the GitHub URL

define_url.py
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

This stores the raw GitHub URL in a Python variable called url.

A variable is a named location used to store a value that you can reuse later.

3. Read the CSV file

read_csv.py
df = pd.read_csv(url)

The pd.read_csv() function reads the CSV file from the URL and converts it into a pandas DataFrame.

The resulting DataFrame is stored in the variable df.

You can now work with the dataset directly in Python.

4. Display the first five rows

head.py
df.head()

The head() method displays the first five rows of the DataFrame by default.

It is a useful way to check whether your dataset has loaded correctly.

Step 3: Check the dataset’s dimensions

After importing the dataset, you can check how many rows and columns it contains.

shape.py
df.shape

The output is a tuple:

shape_output.txt
(150, 5)

The Iris dataset contains 150 rows and 5 columns.

The first number represents the number of rows, while the second represents the number of columns.

This helps you understand the size of your dataset before starting your analysis.

Step 4: Display the column names

To see the names of all columns, use:

columns.py
df.columns

The output will show:

columns_output.txt
Index(['sepal_length', 'sepal_width', 'petal_length',
       'petal_width', 'species'], dtype='object')

Column names identify the variables available in your dataset.

You can use them later to select columns, calculate statistics, visualize data, or train machine learning models.

Step 5: Check the data types

To inspect the data types and basic information about the dataset, use:

info.py
df.info()

This displays:

  • The number of rows.
  • The number of columns.
  • Column names.
  • Data types.
  • Non-null counts.
  • Memory usage.

For example, the flower measurements will generally be represented as numerical values, while the species column will contain text values.

Understanding data types is important before performing data analysis or training a machine learning model.

Step 6: Display the dataset again

You can display the first five rows whenever you need to inspect the data.

head5.py
df.head()

You can also display more rows by passing a number to head().

head10.py
df.head(10)

This displays the first ten rows instead of five.

You now have a dataset loaded directly from GitHub into Google Colab without manually downloading it to your computer.

For beginners

The easiest method for beginners to import a dataset from GitHub

If you only need one publicly accessible CSV file, you do not need to clone an entire GitHub repository or install additional software.

The easiest method is to use the Raw URL with pandas.

Follow these five steps:

  1. Open the GitHub repository.
  2. Click the CSV file you want to use.
  3. Click Raw.
  4. Copy the raw URL and open Google Colab.
  5. Use pd.read_csv() to load the dataset.

Here is the complete example:

easiest_method.py
import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

df = pd.read_csv(url)

print(df.shape)

df.head()

No manual file upload is required. You can read a public CSV directly from GitHub, and pandas will retrieve it when the code runs.

This is generally the best starting point for students working on Python, data science, machine learning, or university projects in Google Colab.

Persist locally

How to download a CSV file from GitHub to Google Colab

Sometimes you may want to download the dataset into Colab’s temporary storage rather than read it directly into pandas.

For example, you may want to keep a local copy of the file during your notebook session, reuse it with multiple scripts, or work with other tools that require a local file path.

You can download a CSV file using Python’s requests library.

Step 1: Download the CSV file

download_csv.py
import requests

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

response = requests.get(url, timeout=30)

response.raise_for_status()

with open("iris.csv", "wb") as file:
    file.write(response.content)

print("Dataset downloaded successfully.")

Explanation of the code

requests.get(url, timeout=30)

This sends an HTTP GET request to the URL to retrieve the file.

The timeout=30 setting allows the request to wait up to 30 seconds before timing out if the server does not respond.

response.raise_for_status()

This checks whether the HTTP request returned an unsuccessful status code, such as 404 or 403, and raises an exception if the request failed.

It helps prevent you from accidentally saving an error response as though it were a dataset.

open("iris.csv", "wb")

This opens a file named iris.csv in binary write mode.

  • w means write.
  • b means binary.

Binary mode is useful when saving downloaded file contents without changing their bytes.

file.write(response.content)

This writes the downloaded content into the local file.

print("Dataset downloaded successfully.")

This displays a message after the file has been written successfully.

Where is the downloaded dataset saved?

In Google Colab, the file is saved in the current working directory, which is usually /content.

You can check the current directory with:

getcwd.py
import os

print(os.getcwd())

You can also list the files available in the directory:

listdir.py
os.listdir()

Step 2: Load the downloaded CSV file using pandas

Once the dataset has been downloaded, you can load it using its local filename.

load_local.py
import pandas as pd

df = pd.read_csv("iris.csv")

df.head()

This time, pandas reads the file from Colab’s local storage rather than directly from GitHub.

Important: Colab’s temporary runtime storage is not permanent. Files saved in the runtime can disappear when the runtime is disconnected, reset, or deleted. If you want to keep your data or results permanently, save them to Google Drive. If you need to save files from your notebook to Drive, see How to Save Files from Colab to Google Drive Automatically.

Convert the link

How to import a dataset from GitHub using a normal URL

You may have copied a URL directly from the GitHub address bar and tried to use it with pandas, only to receive an error.

For example, you might have this URL:

normal_data_url.txt
https://github.com/username/repository/blob/main/data/dataset.csv

This is a normal GitHub file URL. It opens the webpage containing the file preview.

However, when you use this URL with pandas:

wrong_url.py
import pandas as pd

url = "https://github.com/username/repository/blob/main/data/dataset.csv"

df = pd.read_csv(url)

pandas may attempt to interpret the webpage’s HTML content as CSV data, which can result in an error or unexpected output.

How to convert a normal GitHub URL to a Raw URL

For a typical file URL using the blob path, the corresponding raw URL format is:

Normal GitHub URL:

normal_convert.txt
https://github.com/username/repository/blob/main/data/dataset.csv

Raw GitHub URL:

raw_convert.txt
https://raw.githubusercontent.com/username/repository/main/data/dataset.csv

For a typical GitHub URL, the conversion involves:

  1. Replacing github.com with raw.githubusercontent.com.
  2. Removing the blob/ portion of the path.
  3. Keeping the repository name.
  4. Keeping the correct branch name.
  5. Keeping the exact folder path and filename.

The resulting URL should point to the actual file.

Load the dataset using the Raw URL

load_raw.py
import pandas as pd

url = "https://raw.githubusercontent.com/username/repository/main/data/dataset.csv"

df = pd.read_csv(url)

df.head()

The URL above is a placeholder. Replace username, repository, main, and the file path with the actual values from your GitHub repository.

This conversion works for typical GitHub file links, but it is not universal. The file may use a different branch, repository structure, or URL format. It is safer to click Raw and copy the actual link.

More than one file

How to import multiple CSV datasets from GitHub

If your machine learning or data analysis project requires more than one dataset, you can load multiple CSV files from GitHub into separate pandas DataFrames.

For example, suppose a project contains two CSV files hosted in a public GitHub repository.

You can load both files like this:

multiple_csv.py
import pandas as pd

url1 = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
url2 = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv"

df1 = pd.read_csv(url1)
df2 = pd.read_csv(url2)

print("Dataset 1:")
print(df1.head())

print("Dataset 2:")
print(df2.head())

Both URLs above point to CSV files in the publicly accessible seaborn-data repository.

What happens when you import multiple datasets?

The first dataset is stored in df1, while the second dataset is stored in df2.

You can inspect each dataset independently.

df1_shape.py
df1.shape
df2_shape.py
df2.shape

You can also display their columns:

both_columns.py
print(df1.columns)
print(df2.columns)

This approach is useful when a project requires different datasets for comparison, visualization, analysis, or machine learning.

If you need to load many files organized in folders, cloning the repository may be more convenient than copying individual URLs.

Beyond CSV

How to import a dataset from GitHub into Colab using a different file format

GitHub can host more than CSV files. You can also access formats such as JSON, Excel, and plain text using their raw URLs.

The appropriate pandas function depends on the file format.

How to import a JSON file from GitHub

JSON (JavaScript Object Notation) is a format commonly used to store structured data.

If you have a publicly accessible JSON file on GitHub, you can use pd.read_json().

read_json.py
import pandas as pd

url = "https://raw.githubusercontent.com/username/repository/main/data.json"

df = pd.read_json(url)

df.head()

This URL is a placeholder. Replace it with a valid raw JSON file URL.

The JSON structure must be compatible with pandas’ JSON reader. Some nested JSON files require additional processing using json_normalize() or other methods.

How to import an Excel file from GitHub

If your repository contains an Excel file, you can use pd.read_excel().

read_excel.py
import pandas as pd

url = "https://raw.githubusercontent.com/username/repository/main/data.xlsx"

df = pd.read_excel(url)

df.head()

This URL is a placeholder for an Excel file hosted on GitHub.

Pandas may require an additional Excel-reading library, such as openpyxl, depending on the file format and environment.

If needed, install it in Colab:

install_openpyxl.py
!pip install openpyxl

Then run the pd.read_excel() example again.

How to import a TXT file from GitHub

If the text file contains tabular data separated by commas, tabs, or another delimiter, you can often use pd.read_csv().

For a tab-separated file:

read_txt.py
import pandas as pd

url = "https://raw.githubusercontent.com/username/repository/main/data.txt"

df = pd.read_csv(url, sep="\t")

df.head()

This URL is a placeholder. The separator \t represents a tab character. Use the actual separator found in your file.

For plain text that is not structured as a table, you may need Python’s standard requests library or another text-processing method rather than pandas.

Fix it fast

Common errors when importing a dataset from GitHub to Colab and how to fix them

Importing a dataset from GitHub is usually straightforward, but beginners may encounter errors because of incorrect URLs, file permissions, formatting, or encoding.

Here are some common problems and how to fix them.

Error 1 · 404

HTTP Error 404: Not Found

A 404 error indicates that the requested resource could not be found at the URL.

When importing a dataset from GitHub, this may happen because:

  • The filename is incorrect.
  • The file was moved or deleted.
  • The folder path is incorrect.
  • The branch name is incorrect.
  • The URL was copied incorrectly.
  • The repository no longer contains the file.

How to fix a 404 error

Open the GitHub repository in your browser and check that the file exists.

Then:

  1. Navigate to the correct file.
  2. Verify the branch name.
  3. Check the folder path.
  4. Click Raw.
  5. Copy the correct URL.
  6. Try loading the file again in Colab.

You can also check the URL using a simple Python request.

check_status.py
import requests

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

response = requests.get(url, timeout=30)

print(response.status_code)

A status code of 200 generally indicates that the request succeeded. A 404 indicates that the resource was not found at that address.

This check can help you determine whether the URL is correct before using it with pandas.

Error 2 · 403 / 401

HTTP Error 403 or 401

These errors generally indicate that the server is refusing access or that authentication is required.

  • HTTP 403 Forbidden: The server is refusing the request. This may involve permissions, restrictions, or access policies.
  • HTTP 401 Unauthorized: The request requires authentication or valid authorization credentials.

If the dataset belongs to a private GitHub repository, you cannot generally access it through an ordinary public raw URL without appropriate authentication.

How to fix a 403 or 401 error

First, check whether the repository is public or private.

If the repository is public:

  • Verify the URL.
  • Check whether the file is accessible in a browser.
  • Confirm that the URL points to the raw file.
  • Check whether the host is restricting requests.

If the repository is private:

  • Use an appropriate authenticated workflow.
  • Follow GitHub’s authentication and access-token documentation.
  • Avoid placing tokens directly in publicly shared notebooks.
  • Never publish credentials in notebook cells, code repositories, screenshots, or shared outputs.

For sensitive data, consider using a secure storage or authentication workflow rather than a public raw URL.

Error 3 · ParserError

ParserError or Error Tokenizing Data

You may encounter an error such as:

parser_error.txt
ParserError: Error tokenizing data

This usually means pandas cannot correctly interpret the file’s structure.

Possible causes include:

  • The file uses a different delimiter.
  • Some rows contain unexpected values.
  • The file is not actually a CSV.
  • The file contains improperly formatted quotation marks.
  • The file has inconsistent columns.

How to fix a ParserError

First, inspect the file to understand how the data is separated.

For example, a dataset may use semicolons instead of commas.

semicolon_sample.txt
name;age;score
Alice;20;85
Bob;21;92

In this case, use:

sep_semicolon.py
import pandas as pd

df = pd.read_csv(url, sep=";")

df.head()

The sep=";" argument tells pandas to use semicolons instead of commas when separating values.

If the file uses tabs, use:

sep_tab.py
df = pd.read_csv(url, sep="\t")

If you are unsure about the delimiter, you can inspect the raw file in your browser or download a small portion of it to check its structure.

Do not change the delimiter blindly. It must match the actual file.

Error 4 · UnicodeDecodeError

UnicodeDecodeError

A UnicodeDecodeError may occur when pandas tries to read a CSV file using an encoding that does not match the file’s actual text encoding.

UTF-8 is widely used, but some files may use other encodings, such as Latin-1 or Windows-1252.

The error may look like this:

unicode_error.txt
UnicodeDecodeError: 'utf-8' codec can't decode byte ...

How to fix a UnicodeDecodeError

If the file is known to use Latin-1 encoding, you can try:

enc_latin1.py
import pandas as pd

df = pd.read_csv(url, encoding="latin-1")

df.head()

Another possible encoding is Windows-1252:

enc_cp1252.py
df = pd.read_csv(url, encoding="cp1252")

For files containing a UTF-8 byte-order mark, you can try:

enc_utf8sig.py
df = pd.read_csv(url, encoding="utf-8-sig")

The appropriate encoding depends on the actual file. Do not assume that latin-1 will always solve the problem.

Error 5 · Wrong URL

Using the wrong GitHub URL

One of the most common mistakes when importing datasets from GitHub is using the normal repository webpage URL instead of the raw file URL.

For example:

Incorrect URL for a typical CSV import:

incorrect_url.txt
https://github.com/username/repository/blob/main/data.csv

Correct URL format for a typical raw CSV file:

correct_url.txt
https://raw.githubusercontent.com/username/repository/main/data.csv

The normal URL contains blob, which refers to GitHub’s webpage displaying the file.

The raw URL points to the actual file contents.

If you are using pd.read_csv() and the URL does not work, check whether you copied the Raw URL.

Error 6 · Columns

The dataset loads but the columns look incorrect

Sometimes pandas successfully loads the dataset, but the columns appear incorrectly.

For example, you may see a single column containing the entire row:

bad_columns.txt
name;age;score
Alice;20;85
Bob;21;92

This may happen when pandas expects commas but the file uses semicolons.

Another possible problem is an incorrect header setting.

How to fix incorrectly displayed columns

Inspect the dataset:

inspect_head.py
df.head()

If the file uses semicolons, try:

fix_sep.py
df = pd.read_csv(url, sep=";")

df.head()

If the dataset does not contain column names in its first row, you may need to use:

header_none.py
df = pd.read_csv(url, header=None)

The header=None argument tells pandas not to treat the first row as column names.

You can then assign your own column names if necessary:

assign_columns.py
df.columns = ["name", "age", "score"]

Only use this example if the dataset actually contains three columns in the order shown.

Before changing the header or delimiter, inspect the original file so you understand how it is structured.

FAQ

Frequently asked questions

How do I import a dataset from GitHub to Google Colab? +

The easiest way is to copy the Raw URL of a publicly accessible CSV file from GitHub and load it using pandas.

faq_import.py
import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

df = pd.read_csv(url)

df.head()

This loads the dataset directly into Google Colab without manually downloading the file to your computer.

How do I load a CSV file from GitHub using pandas? +

Use pd.read_csv() with the raw GitHub URL.

faq_load.py
import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")

The file will be loaded into a pandas DataFrame that you can use for data analysis.

How do I get the Raw GitHub URL? +

Open the GitHub repository, click the CSV file you want to use, and click the Raw button. Copy the URL from the browser’s address bar.

The raw URL usually starts with https://raw.githubusercontent.com/.

Why does pd.read_csv() not work with my GitHub link? +

You may be using the normal GitHub file webpage URL instead of the raw URL.

A normal GitHub URL generally contains blob, while a raw URL points directly to the file contents.

Open the file on GitHub and click Raw to obtain the correct URL.

Can I import a dataset from GitHub without downloading it? +

Yes. You can use pd.read_csv() with a raw GitHub URL to load a publicly accessible CSV directly into a pandas DataFrame.

You do not need to download the file manually to your computer first.

Can I use GitHub datasets in Google Colab? +

Yes. Google Colab can access publicly accessible files hosted on GitHub.

You can use raw URLs to load individual files or clone a repository if you need multiple files, folders, or an entire project.

How do I download a dataset from GitHub into Colab? +

You can download a file using Python’s requests library.

faq_download.py
import requests

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

response = requests.get(url, timeout=30)
response.raise_for_status()

with open("iris.csv", "wb") as file:
    file.write(response.content)

This saves the file in Colab’s current working directory.

Does Google Colab save datasets permanently? +

No. Files stored in Colab’s temporary runtime storage may disappear when the runtime is reset, disconnected, or deleted.

If you want to keep datasets or processed files permanently, use Google Drive or another persistent storage solution.

Can I import datasets from private GitHub repositories? +

Yes, but private repositories generally require authentication and appropriate permissions.

You must use a secure authentication method to access private files. Avoid exposing access tokens or credentials in publicly shared notebooks.

Conclusion

The one snippet to remember

Importing a dataset from GitHub to Google Colab is one of the easiest ways to start a Python data analysis or machine learning project.

For a publicly accessible CSV file, you generally only need to copy the Raw GitHub URL and use pd.read_csv().

conclusion.py
import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"

df = pd.read_csv(url)

df.head()

This method allows you to load a dataset directly into Google Colab without manually downloading it to your computer.

You can also download datasets into the Colab runtime, import multiple CSV files, work with other file formats, and troubleshoot common errors involving URLs, delimiters, encoding, and file permissions.

Once your dataset is loaded, you can begin exploring the data, creating visualizations, cleaning data, and building machine learning models.

Load a CSV from GitHub in one line

Click Raw on the GitHub file page, copy the raw.githubusercontent.com URL, and pass it straight to pd.read_csv(). No Git, no cloning, no manual download.

See the 5-step method
read_csv(url) Raw URL requests download sep / encoding
Scroll to Top