Pandas 中的分層資料


分層資料通常用於表示巢狀組或類別的多個級別。例如,一家公司可以按職員、部門和地點建立一個人員的層級關係。一個產品可以根據類別和子類別建立一個類別級次。處理分層資料時的其中一個難點是如何以表格格式表示資料,以便於操縱和分析。在本文中,我們將使用 Pandas 內建的方法(如“set_index()”和“groupby()”)來表示分層資料。

使用 Pandas 表示分層資料的 Python 程式

首先,讓我們簡要討論一下上文中提到的 Pandas 和其內建方法

Pandas

這是一個用於資料分析和操縱的開源 Python 庫。它可以處理關係型和帶標註的資料,對指定資料進行各種操作,例如清理、過濾、分組、聚合和合並。這一功能使 Pandas 成為表示分層資料的完美選擇。

要使用 Pandas,我們需要使用以下命令將 Pandas 匯入到我們的程式碼中

import pandas as pd

此處,“pd”是我們為方便起見使用的引用名稱。

set_index()

它用於透過一列或多列來設定給定 datafram 的索引。我們將在這個程式中使用該方法,以用 MultiIndex 表示指定的分級 dataframe。它跟 dataframe 的名稱一起使用。

語法

nameOfDataframe.set_index(nameOfKeys, inplace = True)

引數

nameOfKeys 指定列名稱。

inplace 指定是否修改原始 dataframe。它的預設值為 false,而將其設定為 True 時,原始 dataframe 將被永久修改。

groupby()

該方法用於按照指定條件拆分 dataframe。它提供一種處理分級資料的方法,方法是根據特定列的值將其分成明顯不同的組。它也跟 dataframe 的名稱一起使用。

語法

nameOfDataframe.groupby(nameOfColumn) 

示例 1

下面的示例演示瞭如何在 Pandas 中使用 MultiIndex 建立分層 DataFrame。

方法

  • 首先,匯入 pandas 庫。

  • 然後,建立一個名為 'data' 的字典,它包含四個鍵:'Category'、'Item'、'Price' 和 'Quantity'。每個鍵都有一個列表作為它的對應值。

  • 根據 'data' 字典建立一個 DataFrame 'df',其中每個鍵和值都將成為行和列。

  • 現在,將列 'Category' 和 'Item' 設定為 DataFrame 的索引,以建立一個分層索引。此外,將 'in-place' 設定為 true,這表示對 'df' 物件直接進行更改。

  • 最後,列印 DataFrame 以顯示分層資料並退出。

import pandas as pd
# Creating a user-defined hierarchical DataFrame
data = {
   'Category': ['Fruit', 'Fruit', 'Vegetable', 'Vegetable'],
   'Item': ['Apple', 'Orange', 'Carrot', 'Broccoli'],
   'Price': [1.0, 0.8, 0.5, 0.7],
   'Quantity': [10, 15, 8, 12]
}
df = pd.DataFrame(data)
# redefining the dataframe based on 'Category' and 'Item'
df.set_index(['Category', 'Item'], inplace = True)
# to show the hierarchical data
print(df)

輸出

Category  Item       Price  Quantity             
Fruit     Apple       1.0        10
          Orange      0.8        15
Vegetable Carrot      0.5         8
          Broccoli    0.7        12

示例 2

在下面的示例中,我們將演示在 Pandas 中使用 'groupby()' 方法來根據特定列對資料分組。我們將對前一個示例中使用過的程式碼進行輕微更改。此處,我們會根據 'Category' 列中的唯一值將資料進行分組。它將為每個唯一類別形成單獨的分組。

import pandas as pd
# Creating a user-defined hierarchical DataFrame
data = {
   'Category': ['Fruit', 'Fruit', 'Vegetable', 'Vegetable'],
   'Item': ['Apple', 'Orange', 'Carrot', 'Broccoli'],
   'Price': [1.0, 0.8, 0.5, 0.7],
   'Quantity': [10, 15, 8, 12]
}
df = pd.DataFrame(data)
# redefining the dataframe by grouping based on 'Category'
grouped = df.groupby('Category')
# to display the hierarchical data
for name, group in grouped:
   print(f"Category: {name}") # to represent name of the category 
   print(group) # to print each group
   print()

輸出

Category: Fruit
  Category    Item  Price  Quantity
0    Fruit   Apple    1.0        10
1    Fruit  Orange    0.8        15
Category: Vegetable
    Category      Item  Price  Quantity
2  Vegetable    Carrot    0.5         8
3  Vegetable  Broccoli    0.7        12

示例 3

這是另外一個示例,我們在其中再次對第二個示例的程式碼進行更改。我們將使用 Pandas 中的 groupby() 方法對分層資料分組,並將聚合函式應用到分組後的資料上。agg() 函式採用一個字典作為引數,鍵是我們想要聚合的列,值是我們想要應用到這些列的聚合函式。結果將儲存在一個名為 'grouped' 的新 DataFrame 中。

import pandas as pd
# Creating a user-defined hierarchical DataFrame
data = {
   'Category': ['Fruit', 'Fruit', 'Vegetable', 'Vegetable'],
   'Item': ['Apple', 'Orange', 'Carrot', 'Broccoli'],
   'Price': [1.0, 0.8, 0.5, 0.7],
   'Quantity': [10, 15, 8, 12]
}
df = pd.DataFrame(data)
# redefining the dataframe based on 'Category' and 'Item'
grouped = df.groupby(['Category', 'Item']).agg({'Price': 'sum', 'Quantity': 'sum'})
# to show the dataframe as hierarchical data
print(grouped)

輸出

Category  Item       Price  Quantity              
Fruit     Apple       1.0        10
          Orange      0.8        15
Vegetable Broccoli    0.7        12
          Carrot      0.5         8

結論

在本文中,我們學習了 Pandas 中的幾個內建方法,如 'set_index()' 和 'groupby()'。這些方法使我們能夠輕鬆表示、處理和分析分層資料。set_index() 方法使用 Multiindex 的概念來表示分層資料,而 groupby() 則拆分 dataframe 進行表示。

更新於:25-Jul-2023

2K+ 讀者數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.