Python酷库之旅-第三方库Pandas(021)

目录

一、用法精讲

52、pandas.from_dummies函数

52-1、语法

52-2、参数

52-3、功能

52-4、返回值

52-5、说明

52-6、用法

52-6-1、数据准备

52-6-2、代码示例

52-6-3、结果输出

53、pandas.factorize函数

53-1、语法

53-2、参数

53-3、功能

53-4、返回值

53-5、说明

53-6、用法

53-6-1、数据准备

53-6-2、代码示例

53-6-3、结果输出

54、pandas.unique函数

54-1、语法

54-2、参数

54-3、功能

54-4、返回值

54-5、说明

54-6、用法

54-6-1、数据准备

54-6-2、代码示例

54-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

52、pandas.from_dummies函数
52-1、语法
python 复制代码
# 52、pandas.from_dummies函数
pandas.from_dummies(data, sep=None, default_category=None)
Create a categorical DataFrame from a DataFrame of dummy variables.

Inverts the operation performed by get_dummies().

New in version 1.5.0.

Parameters:
data
DataFrame
Data which contains dummy-coded variables in form of integer columns of 1's and 0's.

sep
str, default None
Separator used in the column names of the dummy categories they are character indicating the separation of the categorical names from the prefixes. For example, if your column names are 'prefix_A' and 'prefix_B', you can strip the underscore by specifying sep='_'.

default_category
None, Hashable or dict of Hashables, default None
The default category is the implied category when a value has none of the listed categories specified with a one, i.e. if all dummies in a row are zero. Can be a single value for all variables or a dict directly mapping the default categories to a prefix of a variable.

Returns:
DataFrame
Categorical data decoded from the dummy input-data.

Raises:
ValueError
When the input DataFrame data contains NA values.

When the input DataFrame data contains column names with separators that do not match the separator specified with sep.

When a dict passed to default_category does not include an implied category for each prefix.

When a value in data has more than one category assigned to it.

When default_category=None and a value in data has no category assigned to it.

TypeError
When the input data is not of type DataFrame.

When the input DataFrame data contains non-dummy data.

When the passed sep is of a wrong data type.

When the passed default_category is of a wrong data type.
52-2、参数

52-2-1、data**(必须)****:**一个DataFrame对象,包含了哑变量(0和1)的列,每列通常表示一个类别的存在或缺失。

52-2-2、sep**(可选,默认值为None)****:**用于分隔哑变量列名中类别信息的分隔符。例如,如果列名是A_cat和A_dog,并且用下划线分隔,那么sep应该设置为 _

52-2-3、default_category**(可选,默认值为None)****:**在原始数据中,可能有一些类别在哑变量中缺失,这个参数允许指定一个默认类别,以便在缺失的情况下使用。

52-3、功能

接受一个包含哑变量的DataFrame,并将其转换回表示原始类别的DataFrame,哑变量通常是通过对分类变量进行独热编码(one-hot encoding)生成的。

52-4、返回值

返回值是一个DataFrame,其中包含了原始的分类数据,这些数据是根据哑变量的值重构的,即每行数据中值为1的哑变量列对应的列名(去掉分隔符和前缀)即为原始分类变量的值。

52-5、说明

该函数非常有用,特别是在对数据进行独热编码之后希望恢复原始分类变量的情况下,它简化了数据预处理模型结果解释的过程。

52-6、用法
52-6-1、数据准备
python 复制代码
52-6-2、代码示例
python 复制代码
# 52、pandas.from_dummies函数
import pandas as pd
# 示例哑变量DataFrame
data = pd.DataFrame({
    'color_red': [1, 0, 0],
    'color_blue': [0, 1, 0],
    'color_green': [0, 0, 1]
})
# 使用pandas.from_dummies将哑变量转换回原始分类数据
original_data = pd.from_dummies(data, sep='_')
print(original_data)
52-6-3、结果输出
python 复制代码
# 52、pandas.from_dummies函数
#    color
# 0    red
# 1   blue
# 2  green
53、pandas.factorize函数
53-1、语法
python 复制代码
# 53、pandas.factorize函数
pandas.factorize(values, sort=False, use_na_sentinel=True, size_hint=None)
Encode the object as an enumerated type or categorical variable.

This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize().

Parameters:
valuessequence
A 1-D sequence. Sequences that aren't pandas objects are coerced to ndarrays before factorization.

sortbool, default False
Sort uniques and shuffle codes to maintain the relationship.

use_na_sentinelbool, default True
If True, the sentinel -1 will be used for NaN values. If False, NaN values will be encoded as non-negative integers and will not drop the NaN from the uniques of the values.

New in version 1.5.0.

size_hintint, optional
Hint to the hashtable sizer.

Returns:
codesndarray
An integer ndarray that's an indexer into uniques. uniques.take(codes) will have the same values as values.

uniquesndarray, Index, or Categorical
The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned.

Note

Even if there's a missing value in values, uniques will not contain an entry for it.
53-2、参数

53-2-1、values**(必须)****:**需要编码的数组或序列,可以是列表、NumPy数组、Pandas系列等。

53-2-2、sort**(可选,默认值为False)****:**是否对唯一值数组进行排序,如果为True,返回的唯一值数组将按字典顺序排序。

53-2-3、use_na_sentinel**(可选,默认值为True)****:**是否在输出整数数组中使用-1作为NaN的标记,如果为False,则将NaN也编码为一个唯一的整数。

53-2-4、size_hint**(可选,默认值为None)****:**一个整数提示,用于内部优化,指示预期的唯一值的数量,这可以提高大规模数据的处理性能。

53-3、功能

将一组值(如列表、数组或序列)编码为整数索引。具体来说,它会为每个唯一值分配一个唯一的整数,并返回这些整数索引以及唯一值的数组。

53-4、返回值

返回两个对象:

53-4-1、整数索引数组:一个与输入数组大小相同的整数数组,其中每个整数对应于输入数组中的一个值。

53-4-2、唯一值数组:一个包含输入数组中所有唯一值的数组,按它们首次出现的顺序排列,除非使用sort=True参数。

53-5、说明

pandas.factorize的主要功能是:

53-5-1、将类别数据转换为整数索引:通过为每个唯一值分配一个整数,使得类别数据可以用于数值计算或进一步分析。

53-5-2、处理缺失值:可以选择是否将缺失值(NaN)编码为一个特定的整数(默认为-1)。

53-6、用法
53-6-1、数据准备
python 复制代码
53-6-2、代码示例
python 复制代码
# 53、pandas.factorize函数
# 53-1、基本用法
import pandas as pd
values = ['a', 'b', 'a', 'c', 'b']
factorized_values, unique_values = pd.factorize(values)
print(factorized_values)
print(unique_values)

# 53-2、使用sort参数
import pandas as pd
values = ['a', 'b', 'a', 'c', 'b']
factorized_values, unique_values = pd.factorize(values, sort=True)
print(factorized_values)
print(unique_values)

# 53-3、处理NaN
import pandas as pd
values_with_nan = ['a', 'b', None, 'a', 'c']
factorized_values, unique_values = pd.factorize(values_with_nan, use_na_sentinel=True)
print(factorized_values)
print(unique_values)

# 53-4、使用size_hint参数
import pandas as pd
large_values = ['a'] * 100000 + ['b'] * 100000
factorized_values, unique_values = pd.factorize(large_values, size_hint=2)
print(factorized_values[:10])
print(unique_values)
53-6-3、结果输出
python 复制代码
# 53、pandas.factorize函数
# 53-1、基本用法
# [0 1 0 2 1]
# ['a' 'b' 'c']

# 53-2、使用sort参数
# [0 1 0 2 1]
# ['a' 'b' 'c']

# 53-3、处理NaN
# [ 0  1 -1  0  2]
# ['a' 'b' 'c']

# 53-4、使用size_hint参数
# [0 0 0 0 0 0 0 0 0 0]
# ['a' 'b']
54、pandas.unique函数
54-1、语法
python 复制代码
# 54、pandas.unique函数
pandas.unique(values)
Return unique values based on a hash table.

Uniques are returned in order of appearance. This does NOT sort.

Significantly faster than numpy.unique for long enough sequences. Includes NA values.

Parameters:
values
1d array-like
Returns:
numpy.ndarray or ExtensionArray
The return can be:

Index : when the input is an Index

Categorical : when the input is a Categorical dtype

ndarray : when the input is a Series/ndarray

Return numpy.ndarray or ExtensionArray.
54-2、参数

54-2-1、values **(必须):**可以是以下几种类型的对象:

  • 一维的pandas.Series
  • 一维的pandas.Index
  • 一维的numpy.ndarray
  • 一维的列表或序列
54-3、功能

返回输入数组中的唯一值,按它们在数组中首次出现的顺序排列。

54-4、返回值

返回一个numpy.ndarray,其中包含输入数组中的唯一值。

54-5、说明

pandas.unique是一个简单且高效的函数,用于从一维数组、Series或Index中提取唯一值,它只需要一个参数,即要处理的数组,并返回一个包含唯一值的numpy.ndarray,这种功能在数据预处理清理阶段非常有用,可以帮助识别数据集中的独特元素。

54-6、用法
54-6-1、数据准备
python 复制代码
54-6-2、代码示例
python 复制代码
# 54、pandas.unique函数
# 54-1、处理列表
import pandas as pd
values = [1, 2, 2, 3, 4, 4, 4, 5]
unique_values = pd.unique(values)
print(unique_values)

# 54-2、处理pandas Series
import pandas as pd
series = pd.Series(['a', 'b', 'a', 'c', 'b', 'd'])
unique_values = pd.unique(series)
print(unique_values)

# 54-3、处理numpy数组
import pandas as pd
import numpy as np
array = np.array([1, 2, 3, 1, 2, 3, 4])
unique_values = pd.unique(array)
print(unique_values)

# 54-4、处理含有NaN的数据
import pandas as pd
values_with_nan = [1, 2, np.nan, 2, np.nan, 3]
unique_values = pd.unique(values_with_nan)
print(unique_values)
54-6-3、结果输出
python 复制代码
# 54、pandas.unique函数
# 54-1、处理列表
# [1 2 3 4 5]

# 54-2、处理pandas Series
# ['a' 'b' 'c' 'd']

# 54-3、处理numpy数组
# [1 2 3 4]

# 54-4、处理含有NaN的数据
# [ 1.  2. nan  3.]

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
相关推荐
想回家的一天5 小时前
ECONNREFUSED ::1:8000 前端代理问题
开发语言
cike_y5 小时前
Mybatis之解析配置优化
java·开发语言·tomcat·mybatis·安全开发
Jay_Franklin6 小时前
SRIM通过python计算dap
开发语言·python
是一个Bug6 小时前
Java基础50道经典面试题(四)
java·windows·python
Slow菜鸟6 小时前
Java基础架构设计(三)| 通用响应与异常处理(分布式应用通用方案)
java·开发语言
吴佳浩7 小时前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
消失的旧时光-19437 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir7 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
tap.AI7 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
阿蒙Amon7 小时前
C#每日面试题-重写和重载的区别
开发语言·c#