Pandas 层次化数据

Pandas 层次化数据

层次化数据通常用于表示多个级别的嵌套组或类别。例如,一个公司可能有雇员、部门和位置的层次结构。产品可能有类别和子类别的层次结构。处理层次化数据的一个挑战是如何将其表示为可以轻松操作和分析的表格格式。在本文中,我们将使用Pandas的内置方法如’set_index() ‘和’groupby()’来呈现层次化数据。

使用Pandas表示层次化数据的Python程序

首先,让我们简要讨论一下Pandas及其在前一部分提到的内置方法:

Pandas

Pandas是一个开源的Python库,主要用于数据分析和处理。它可以通过对指定数据执行各种操作,如清理、过滤、分组、聚合和合并,来处理关系和标记数据。这个特性使它成为表示层次化数据的理想选择。

要使用Pandas,我们需要使用以下命令将其导入我们的代码中:

import pandas as pd

这里,’pd’是我们方便起见使用的引用名称。

set_index()

它用于使用一个或多个列设置给定DataFrame的索引。我们将在我们的程序中使用此方法来表示具有MultiIndex的指定分层DataFrame。它与DataFrame的名称一起使用。

语法

nameOfDataframe.set_index(nameOfKeys, inplace = True)

参数

nameOfKeys :指定列名。

inplace :指定是否修改原始数据帧。其默认值为false,当设置为True时,原始数据帧会被永久修改。

groupby()

此方法用于根据指定的条件拆分数据帧。它提供了一种处理分层数据的方法,通过根据特定列的值将其分为不同的组。它也与数据帧的名称一起使用。

语法

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() 方法使用了多级索引的概念来呈现分层数据,而groupby() 方法则将数据框拆分以呈现。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程