64 KiB
Inputs and Outputs¶
Data Input and Output¶
This notebook is the reference code for getting input and output, pandas can read a variety of file types using its pd.read_ methods. Let's take a look at the most common data types:
import numpy as np
import pandas as pd
Check out the references here!¶
This is the best online resource for how to read/write to a variety of data sources!
https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
Format Type | Data Description | Reader | Writer |
---|---|---|---|
text | CSV | read_csv | to_csv |
text | JSON | read_json | to_json |
text | HTML | read_html | to_html |
text | Local clipboard | read_clipboard | to_clipboard |
binary | MS Excel | read_excel | to_excel |
binary | OpenDocument | read_excel | |
binary | HDF5 Format | read_hdf | to_hdf |
binary | Feather Format | read_feather | to_feather |
binary | Parquet Format | read_parquet | to_parquet |
binary | Msgpack | read_msgpack | to_msgpack |
binary | Stata | read_stata | to_stata |
binary | SAS | read_sas | |
binary | Python Pickle Format | read_pickle | to_pickle |
SQL | SQL | read_sql | to_sql |
SQL | Google Big Query | read_gbq | to_gbq |
Reading in a CSV¶
Comma Separated Values files are text files that use commas as field delimeters.
Unless you're running the virtual environment included with the course, you may need to install xlrd and openpyxl.
In your terminal/command prompt run:
conda install xlrd
conda install openpyxl
Then restart Jupyter Notebook. (or use pip install if you aren't using the Anaconda Distribution)
Understanding File Paths¶
You have two options when reading a file with pandas:
If your .py file or .ipynb notebook is located in the exact same folder location as the .csv file you want to read, simply pass in the file name as a string, for example:
df = pd.read_csv('some_file.csv')
Pass in the entire file path if you are located in a different directory. The file path must be 100% correct in order for this to work. For example:
df = pd.read_csv("C:\\Users\\myself\\files\\some_file.csv")
Print your current directory file path with pwd¶
pwd
List the files in your current directory with ls¶
ls
NOTE! Common confusion point! Take note that all read input methods are called directly from pandas with pd.read_ , all output methods are called directly off the dataframe with df.to_¶
CSV Input¶
df = pd.read_csv('example.csv')
df
df = pd.read_csv('example.csv',index_col=0)
df
df = pd.read_csv('example.csv')
df
CSV Output¶
Set index=False if you do not want to save the index , otherwise it will add a new column to the .csv file that includes your index and call it "Unnamed: 0" if your index did not have a name. If you do want to save your index, simply set it to True (the default value).
df.to_csv('new_file.csv',index=False)
HTML¶
Pandas can read table tabs off of HTML. This only works if your firewall isn't blocking pandas from accessing the internet!
Unless you're running the virtual environment included with the course, you may need to install lxml, htmllib5, and BeautifulSoup4.
In your terminal/command prompt run:
conda install lxml
or
pip install lxml
Then restart Jupyter Notebook (you may need to restart your computer). (or use pip install if you aren't using the Anaconda Distribution)
read_html¶
HTML Input¶
Pandas read_html function will read tables off of a webpage and return a list of DataFrame objects. NOTE: This only works with well defined objects in the html on the page, this can not magically read in tables that are images on a page.
tables = pd.read_html('https://en.wikipedia.org/wiki/World_population')
len(tables) #tables
Not Useful Tables¶
Pandas found 26 tables on that page. Some are not useful:
tables[0]
0 | 1 | |
---|---|---|
0 | NaN | An editor has expressed concern that this arti... |
Tables that need formatting¶
Some will be misaligned, meaning you need to do extra work to fix the columns and rows:
tables[1]
world_pop = tables[1]
world_pop.columns
world_pop = world_pop['World population (millions, UN estimates)[14]'].drop('#',axis=1)
world_pop.columns
world_pop.columns = ['Countries', '2000', '2015', '2030 Est.']
world_pop = world_pop.drop(11,axis=0)
world_pop
Tables that are intact¶
tables[6]
Write to html Output¶
If you are working on a website and want to quickly output the .html file, you can use to_html
df.to_html('simple.html',index=False)
read_html is not perfect, but its quite powerful for such a simple method call!
Excel Files¶
Pandas can read in basic excel files (it will get errors if there are macros or extensive formulas relying on outside excel files), in general, pandas can only grab the raw information from an .excel file.
NOTE: Requires the openpyxl and xlrd library! Its provided for you in our environment, or simply install with:¶
pip install openpyxl
pip install xlrd
Heavy excel users may want to check out this website: https://www.python-excel.org/
You can think of an excel file as a Workbook containin sheets, which for pandas means each sheet can be a DataFrame.
Excel file input with read_excel()¶
df = pd.read_excel('my_excel_file.xlsx',sheet_name='First_Sheet')
df
What if you don't know the sheet name? Or want to run a for loop for certain sheet names? Or want every sheet?¶
Several ways to do this: https://stackoverflow.com/questions/17977540/pandas-looking-up-the-list-of-sheets-in-an-excel-file
# Returns a list of sheet_names
pd.ExcelFile('my_excel_file.xlsx').sheet_names
Grab all sheets¶
excel_sheets = pd.read_excel('my_excel_file.xlsx',sheet_name=None)
type(excel_sheets)
excel_sheets.keys()
excel_sheets['First_Sheet']
Write to Excel File¶
df.to_excel('example.xlsx',sheet_name='First_Sheet',index=False)
SQL Connections¶
NOTE: Highly recommend you explore specific libraries for your specific SQL Engine. Simple search for your database+python in Google and the top results should hopefully include an API.¶
Let's review pandas capabilities by using SQLite, which comes built in with Python.
Example SQL Database (temporary in your RAM)¶
You will need to install sqlalchemy with:
pip install sqlalchemy
to follow along. To understand how to make a connection to your own database, make sure to review: https://docs.sqlalchemy.org/en/13/core/connections.html
from sqlalchemy import create_engine
temp_db = create_engine('sqlite:///:memory:')
Write to Database¶
tables[6]
pop = tables[6]
pop.to_sql(name='populations',con=temp_db)
Read from SQL Database¶
# Read in an entire table
pd.read_sql(sql='populations',con=temp_db)
# Read in with a SQL Query
pd.read_sql_query(sql="SELECT Country FROM populations",con=temp_db)
It is difficult to generalize pandas and SQL, due to a wide array of issues, including permissions,security, online access, varying SQL engines, etc... Use these ideas as a starting off point, and you will most likely need to do your own research for your own situation.