How to Import CSV and XLS Data into Pandas

m0nica

Monica Powell

Posted on November 26, 2017

How to Import CSV and XLS Data into Pandas

Pandas
Pandas is a Python Data Analysis Library. It allows you to play around with data and perform powerful data analysis.

In this example I will show you how to read data from CSV and Excel files in Pandas. You can then save the read output as in a Pandas dataframe. The sample data used in the below exercise was generated by https://mockaroo.com/.

import pandas as pd
Enter fullscreen mode Exit fullscreen mode
csv_data_df = pd.read_csv('data/MOCK_DATA.csv')
Enter fullscreen mode Exit fullscreen mode

Preview the first 5 lines of the data with .head() to ensure that it loaded.

csv_data_df.head()
Enter fullscreen mode Exit fullscreen mode
.dataframe thead tr:only-child th {
    text-align: right;
}

.dataframe thead th {
    text-align: left;
}

.dataframe tbody tr th {
    vertical-align: top;
}
Enter fullscreen mode Exit fullscreen mode
id first_name last_name email gender ip_address
0 1 Ross Ricart rricart0@berkeley.edu Male 217.151.154.186
1 2 Jenn Pizer jpizer1@usnews.com Female 104.123.13.234
2 3 Delainey Sulley dsulley2@xing.com Male 6.101.0.150
3 4 Nessie Feirn nfeirn3@samsung.com Female 97.93.173.170
4 5 Noami Flanner nflanner4@woothemes.com Female 174.228.138.242

You will need to pip install xlrd if you haven't already. In order to import data from Excel.

import xlrd
excel_data_df = pd.read_excel('data/MOCK_DATA.xlsx')
Enter fullscreen mode Exit fullscreen mode
excel_data_df.head()
Enter fullscreen mode Exit fullscreen mode
.dataframe thead tr:only-child th {
    text-align: right;
}

.dataframe thead th {
    text-align: left;
}

.dataframe tbody tr th {
    vertical-align: top;
}
Enter fullscreen mode Exit fullscreen mode
id first_name last_name email gender ip_address
0 1 Chloris Antliff cantliff0@shareasale.com Female 131.17.2.171
1 2 Brion Gierok bgierok1@posterous.com Male 245.41.126.3
2 3 Fleur Skells fskells2@creativecommons.org Female 75.0.34.132
3 4 Dora Privost dprivost3@newsvine.com Female 51.202.4.39
4 5 Annabella Hucker ahucker4@typepad.com Female 124.80.181.41

Image Courtesy of jballeis (Own work) CC BY-SA 3.0, via Wikimedia Commons

A version of this article was originally published by Monica Powell on www.datalogues.com

💖 💪 🙅 🚩
m0nica
Monica Powell

Posted on November 26, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024