如何使用 Pandas 在 Python 中建立透視表?
透視表是一個強大的資料分析工具,允許您根據不同的維度彙總和聚合資料。在 Python 中,您可以使用 pandas 庫建立透視表,該庫提供了靈活且高效的資料處理和分析工具。
要在 pandas 中建立透視表,您首先需要在 pandas DataFrame 中擁有一個數據集。您可以從各種來源(例如 CSV 檔案、Excel 電子表格、SQL 資料庫等)將資料載入到 DataFrame 中。
一旦您的資料在 DataFrame 中,您可以使用 pandas 的 `pivot_table()` 函式建立透視表。以下是其語法:
dataframe.pivot(self, index=None, columns=None, values=None, aggfunc)
`pivot_table()` 函式接受多個引數,包括要使用的 DataFrame、索引列、用作透視表列的列以及要聚合的值列。您還可以指定要使用的聚合函式,例如 sum、mean、max、min 等。
在我們深入研究 pivot 和 `pivot_table()` 函式之前,讓我們首先建立一個我們將要使用的 DataFrame。
Pandas 中的 DataFrame
在 pandas 中,DataFrame 是一種二維帶標籤的資料結構,其列可能具有不同的型別。它是 pandas 中用於資料處理和分析的主要資料結構。
DataFrame 可以看作是電子表格或 SQL 表,具有行和列。它允許輕鬆處理和操作資料,包括索引、選擇、過濾、合併和分組。
考慮以下程式碼。此程式碼使用 Python 字典建立了一個名為 df 的 DataFrame 物件,其中包含四列:“產品”、“類別”、“數量”和“金額”。字典的每個鍵對應於列的名稱,其值是包含該列值的列表。
示例
# importing pandas library import pandas as pd # creating a dataframe from a dictionary # creating a column 'Product', 'Category', 'Quantity','Amount' with its values df = pd.DataFrame({ 'Product': ['Litchi', 'Broccoli', 'Banana', 'Banana', 'Beans', 'Orange', 'Mango', 'Banana'], 'Category': ['Fruit', 'Vegetable', 'Fruit', 'Fruit', 'Vegetable', 'Fruit', 'Fruit', 'Fruit'], 'Quantity': [8, 5, 3, 4, 5, 9, 11, 8], 'Amount': [270, 239, 617, 384, 626, 610, 62, 90] }) # print the dataframe print(df)
輸出
執行此程式碼時,它將在終端上產生以下輸出:
Product Category Quantity Amount 0 Litchi Fruit 8 270 1 Broccoli Vegetable 5 239 2 Banana Fruit 3 617 3 Banana Fruit 4 384 4 Beans Vegetable 5 626 5 Orange Fruit 9 610 6 Mango Fruit 11 62 7 Banana Fruit 8 90
使用 Pandas 建立透視表
現在讓我們使用 `pivot_table()` 函式建立一個總銷售額的透視表。考慮以下程式碼。
示例
# importing pandas library import pandas as pd # creating a dataframe from a dictionary # creating a column 'Product', 'Category', 'Quantity','Amount' with its values df = pd.DataFrame({ 'Product': ['Litchi', 'Broccoli', 'Banana', 'Banana', 'Beans', 'Orange', 'Mango', 'Banana'], 'Category': ['Fruit', 'Vegetable', 'Fruit', 'Fruit', 'Vegetable', 'Fruit', 'Fruit', 'Fruit'], 'Quantity': [8, 5, 3, 4, 5, 9, 11, 8], 'Amount': [270, 239, 617, 384, 626, 610, 62, 90] }) # creating pivot table of total sales # product-wise pivot = df.pivot_table(index =['Product'], values =['Amount'], aggfunc ='sum') print(pivot) # print the dataframe print(df)
解釋
它建立了一個名為 df 的 DataFrame 物件,其中包含四列:“產品”、“類別”、“數量”和“金額”。每一列都有自己的值,它們是使用 Python 字典建立的。
之後,程式碼使用 `pivot_table()` 函式建立一個按產品分組的銷售資料透視表,並計算每個產品的總銷售額。
最後,透視表被列印到控制檯以顯示每個產品的總銷售資料,並且原始 DataFrame 也被列印到控制檯以顯示生成透視表的原始資料。
輸出
執行後,您將在終端上獲得以下輸出:
Product Amount Banana 1091 Beans 626 Broccoli 239 Litchi 270 Mango 62 Orange 610 Product Category Quantity Amount 0 Litchi Fruit 8 270 1 Broccoli Vegetable 5 239 2 Banana Fruit 3 617 3 Banana Fruit 4 384 4 Beans Vegetable 5 626 5 Orange Fruit 9 610 6 Mango Fruit 11 62 7 Banana Fruit 8 90
結論
總之,使用 pandas 庫在 Python 中建立透視表是分析表格資料和提取有意義見解的強大方法。透過分組資料和計算聚合值,透視表可以幫助您識別資料中可能難以看到的模式和趨勢。憑藉 pandas 提供的靈活性和易用性,建立透視表從未如此簡單。
按照本教程中概述的步驟,您現在應該已經掌握了在 Python 中建立和使用透視表的堅實基礎。