套件

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

模組就是 Python 檔案

  • 模組 = Python 檔案

  • 任何人都能建立 Python 檔案!

筆電上的程式碼檔案

Intermediate Python for Developers

套件

  • 多個模組的集合 = Package
    • 也稱為 library
  • 公開可用且免費
  • 從 PyPI 下載
  • 之後即可像模組一樣匯入並使用

大型紙箱

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

安裝套件

  • Terminal / Command Prompt

    python3 -m pip install <package_name>
    
  • python3-在終端機執行 Python 程式碼

  • pip-首選安裝工具

程式碼終端機

Intermediate Python for Developers

安裝套件

 

python3 -m pip install pandas

Pandas 標誌

$$

  • 處理與分析資料的套件
Intermediate Python for Developers

使用別名匯入

# Import pandas
import pandas
  • 使用別名可縮短程式碼
# Import pandas using an alias
import pandas as pd
Intermediate Python for Developers

建立 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)
print(sales_df)
  user_id  order_value
0    KM37       197.75
1    PR19       208.21
2    YU88       134.99
Intermediate Python for Developers

讀取 CSV 檔案

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

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

預覽檔案

# DataFrame method to preview the first five rows
print(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

檢查檔案資訊

# Checking the file info
print(sales_df.info())
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
 #   Column       Non-Null Count  Dtype  
<hr />  ------       --------------  -----  
 0   user_id      3 non-null      object 
 1   order_value  3 non-null      float64
dtypes: float64(1), object(1)
memory usage: 180.0+ bytes
Intermediate Python for Developers

函式 vs. 方法

# This is a built-in function
print(sum([1, 2 ,3, 4, 5]))
15
  • 函式 = 執行特定任務的程式碼
# This is a pandas function
sales_df = pd.DataFrame(sales)
  • .head() 只適用於 pandas 的 DataFrame
# This is a method
print(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

一起來練習吧!

Intermediate Python for Developers

Preparing Video For Download...