Python Pandas Series.factize()

Python Pandas Series.factize()

Pandas系列是一个带有轴标签的一维ndarray。标签不需要是唯一的,但必须是一个可散列的类型。该对象支持基于整数和标签的索引,并提供了大量的方法来执行涉及索引的操作。

Pandas Series.factize()函数将对象编码为一个枚举类型或分类变量。这个方法对于获得一个数组的数字表示很有用,当所有重要的是识别不同的值。

语法: Series.factorize(sort=False, na_sentinel=-1)

参数:
sort :对uniques进行排序,并对标签进行洗牌以保持关系。
na_sentinel :标记 “未找到 “的值。

返回值 :
标签 : ndarray
uniques : ndarray, Index, or Categorical

例子#1:使用Series.factize()函数对给定的系列对象的基础数据进行编码。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio'])
  
# Create the Index
sr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

Python Pandas Series.factize()
现在我们将使用Series.factize()函数对给定系列对象的基础数据进行编码。

# encode the values
result = sr.factorize()
  
# Print the result
print(result)

输出 :
Python Pandas Series.factize()
正如我们在输出中看到的,Series.factorize()函数已经成功地对给定系列对象的基础数据进行了编码。注意缺失值已经被分配了一个-1的代码。

示例#2 :使用Series.factize()函数对给定的系列对象的基础数据进行编码。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([80, 25, 3, 80, 24, 25])
  
# Create the Index
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :
Python Pandas Series.factize()

现在我们将使用Series.factize()函数对给定系列对象的基础数据进行编码。

# encode the values
result = sr.factorize()
  
# Print the result
print(result)

输出 :
Python Pandas Series.factize()
正如我们在输出中看到的,Series.factize()函数已经成功地编码了给定系列对象的基础数据。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程