Pandas 分类数据

分类数据是一种数据类型,它代表类别或标签,而不是数值。

简单来说,它是一种将数据归入预定义类别的分类方法,例如性别、国家名称或教育水平。

当我们拥有的数据自然适合预定义的选项时,分类数据就很有用。


在 Pandas 中创建分类数据类型

在 Pandas 中,Categorical() 方法用于从给定的值序列创建分类数据类型。

import pandas as pd

data = ['red', 'blue', 'green', 'red', 'blue']

# create a categorical column
categorical_data = pd.Categorical(data)

print(categorical_data)

输出

['red', 'blue', 'green', 'red', 'blue']
Categories (3, object): ['blue', 'green', 'red']

在上面的示例中,Categorical() 函数将 data 列表转换为分类序列。

输出包括原始数据值和数据中存在的唯一类别列表。


将 Pandas Series 转换为 Categorical Series

在 Pandas 中,我们可以使用 astype() 函数或 pd.Series() 构造函数中的 dtype 参数,将常规的 Pandas Series 转换为 Categorical Series。

使用 astype() 函数

import pandas as pd

# create a regular Series
data = ['red', 'blue', 'green', 'red', 'blue']
series1 = pd.Series(data)

# convert the Series to a categorical Series using .astype()
categorical_s = series1.astype('category')

print(categorical_s)

输出

0      red
1     blue
2    green
3      red
4     blue
dtype: category
Categories (3, object): ['blue', 'green', 'red']

这里,series1.astype('category') 指定我们要将 series1 系列转换为分类系列。

在 Series() 中使用 dtype 参数

import pandas as pd

# create a categorical Series
data = ['A', 'B', 'A', 'C', 'B']
cat_series = pd.Series(data, dtype="category")

print(cat_series)

在这里,我们在 Series() 中使用了 dtype="category" 参数,将普通系列转换为分类系列。

输出将与上面相同。


在 Pandas 中访问类别和代码

在 Pandas 中,cat 访问器允许我们访问类别和代码。以下是 cat 访问器提供的用于访问类别和代码的属性:

  • categories - 返回分类变量中存在的唯一类别
  • codes - 返回代表分类变量中每个元素的类别的整数代码

让我们看一个例子。

import pandas as pd

# create a categorical Series
data = ['A', 'B', 'A', 'C', 'B']
cat_series = pd.Series(data, dtype="category")

# using .cat accessor
print(cat_series.cat.categories)
print(cat_series.cat.codes)

输出

Index(['A', 'B', 'C'], dtype='object')
0    0
1    1
2    0
3    2
4    1
dtype: int8

在上面的示例中,我们首先使用了 cat_series.cat.categories 来访问 cat_series 中存在的唯一类别。

在这种情况下,输出将是 Index(['A', 'B', 'C'], dtype='object'),这是数据中的不同类别。

然后,我们使用了 cat_series.cat.codes 来访问 cat_series 中类别对应的整数代码。

让我们看看我们是如何得到输出的:

0    0
1    1
2    0
3    2
4    1

这里,

  1. cat_series 中索引为 **0** 的元素是 A,它对应于类别 **0**。
  2. cat_series 中索引为 **1** 的元素是 B,它对应于类别 **1**。
  3. cat_series 中索引为 **2** 的元素是 A,它再次对应于类别 **0**。
  4. cat_series 中索引为 **3** 的元素是 C,它对应于类别 **2**。
  5. cat_series 中索引为 **4** 的元素是 B,它再次对应于类别 **1**。

在 Pandas 中重命名类别

我们可以使用 cat.rename_categories() 方法在 Pandas 中重命名类别。例如:

import pandas as pd

# create a categorical Series
data = ['A', 'B', 'A', 'C', 'B']
cat_series = pd.Series(data, dtype="category")

# create a dictionary for renaming categories
category_mapping = {"A": "Category A", "B": "Category B", "C": "Category C"}

# rename categories using .rename_categories() and recreate the Series
cat_series_renamed = cat_series.cat.rename_categories(category_mapping)

print(cat_series_renamed)

输出

0    Category A
1    Category B
2    Category A
3    Category C
4    Category B
dtype: category
Categories (3, object): ['Category A', 'Category B', 'Category C']

在此示例中,类别 ABC 已分别重命名为 Category ACategory BCategory C


在 Pandas 中添加新类别

在 Pandas 中,我们可以使用 cat.add_categories() 方法将新类别添加到现有类别集中。

让我们看一个例子。

import pandas as pd

# create a categorical Series
data = ['A', 'B', 'A', 'C', 'B']
cat_series = pd.Series(data, dtype="category")

# add new categories and reassign the variable
new_categories = ['D', 'E']
cat_series = cat_series.cat.add_categories(new_categories)

print(cat_series)

输出

0    A
1    B
2    A
3    C
4    B
dtype: category
Categories (5, object): ['A', 'B', 'C', 'D', 'E']

在这里,我们将新类别 DE 添加到分类序列中,并将结果分配回 cat_series,从而有效地使用新类别更新该变量。


在 Pandas 中删除类别

要从 Pandas 的分类变量中删除类别,我们可以使用 cat.remove_categories() 方法。

让我们看一个例子。

import pandas as pd

# create a categorical Series
data = ['A', 'B', 'A', 'C', 'B']
cat_series = pd.Series(data, dtype="category")

# display the original categorical variable
print("Original Series:")
print(cat_series)

# remove specific categories
categories_to_remove = ["B", "C"]
cat_series_removed = cat_series.cat.remove_categories(categories_to_remove)

# display the modified categorical variable
print("\nModified Series:")
print(cat_series_removed)

输出

Original Series:
0    A
1    B
2    A
3    C
4    B
dtype: category
Categories (3, object): ['A', 'B', 'C']
Modified Series:
0      A
1    NaN
2      A
3    NaN
4    NaN
dtype: category
Categories (1, object): ['A']

在此示例中,我们使用 cat.remove_categories()cat_series 中删除了类别 BC


检查分类变量是否已排序

在 Pandas 中,要检查分类变量是否已排序,您可以使用 Pandas 中 cat 访问器提供的 ordered 属性。例如:

import pandas as pd

# create an ordered categorical Series
data = ['low', 'medium', 'high', 'low', 'medium']
ordered_cat_series = pd.Categorical(data, categories=['low', 'medium', 'high'], ordered=True)

# check if the categorical variable is ordered
is_ordered = ordered_cat_series.ordered

print("Is ordered:", is_ordered)

输出

Is ordered: True

在此示例中,ordered_cat_series.ordered 将为 True,因为 ordered_cat_series 分类变量是使用 ordered=True 参数创建的。

注意:在 Pandas 中对分类变量进行排序有助于为分析和可视化维护逻辑顺序。认识到这种顺序可以确保准确的统计测试、有意义的视觉表示和一致的数据解释。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战