Packages

Intermediate Python for Developers

George Boorman

Curriculum Manager, DataCamp

Modules are Python files

  • Module = Python file

  • Anyone can create a Python file!

Code file on a laptop

1 Image source: https://unsplash.com/@jstrippa
Intermediate Python for Developers

Packages

  • A collection of modules = Package
    • Might also hear it called a library
  • Packages are publicly available and free
  • First need to be downloaded from PyPI
  • Then can be imported and used like modules

Large cardboard box

1 https://pypi.org/
Intermediate Python for Developers

Installing a package

  • Terminal / Command Prompt
    • Allows us to run commands to perform tasks
python3 -m pip install <package_name>
  • python3 - Used to execute Python code from the terminal
  • pip - Preferred Installer Program
Intermediate Python for Developers

Installing a package

 

python3 -m pip install pandas

Pandas logo.png

Intermediate Python for Developers

Importing with an alias

# Import pandas
import pandas
  • Need to write pandas before every function
# Import pandas using an alias
import pandas as pd
Intermediate Python for Developers

Creating a DataFrame

# Sales dictionary
sales = {"user_id": ["KM37", "PR19", "YU88"],
         "order_value": [197.75, 208.21, 134.99]}

# Convert to a pandas DataFrame sales_df = pd.DataFrame(sales)
sales_df
  user_id  order_value
0    KM37       197.75
1    PR19       208.21
2    YU88       134.99
Intermediate Python for Developers

Reading in a CSV file

# Reading in a CSV file in our current directory
sales_df = pd.read_csv("sales.csv")

# Checking the data type type(sales_df)
pandas.core.frame.DataFrame
Intermediate Python for Developers

Previewing the file

# DataFrame method to preview the first five rows
sales_df.head()
  user_id  order_value
0    KM37       197.75
1    PR19       208.21
2    YU88       134.99
3    NT43       153.54        
4    IW06       379.47
Intermediate Python for Developers

Functions versus methods

  • Function = code to perform a task

  • Method = a function that is specific to a data type

Intermediate Python for Developers

Functions versus methods

# This is a built-in function
sum([1, 2 ,3, 4, 5])
15
# This is a pandas function
sales_df = pd.DataFrame(sales)
  • .head() won't work with other data types:
    • e.g., lists, dictionaries
# This is a method
# It is specific to a DataFrame data type
sales_df.head()
  user_id  order_value
0    KM37       197.75
1    PR19       208.21
2    YU88       134.99
3    NT43       153.54        
4    IW06       379.47
Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...