用法:
Series.factorize(sort=False, na_sentinel=- 1)将对象编码为枚举类型或分类变量。
当重要的是识别不同的值时,此方法对于获取数组的数字表示很有用。
factorize既可用作顶级函数pandas.factorize(),也可用作方法Series.factorize()和Index.factorize()。- sort:布尔值,默认为 False
排序
uniques并打乱codes以保持关系。- na_sentinel:int 或无,默认 -1
标记“not found”的值。如果没有,将不会从值的唯一性中删除 NaN。
- codes:ndarray
一个整数 ndarray,它是
uniques的索引器。uniques.take(codes)将具有与values相同的值。- uniques:ndarray、索引或分类
唯一的有效值。当
values为分类时,uniques为分类。当values是其他一些 pandas 对象时,返回一个Index。否则,返回一维 ndarray。注意
即使有缺失值
values,uniques将要不是包含一个条目。
参数:
返回:
注意:
有关更多示例,请参阅用户指南。
例子:
这些示例都将 factorize 显示为顶级方法,例如
pd.factorize(values)。对于像Series.factorize()这样的方法,结果是相同的。>>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b']) >>> codes array([0, 0, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object)使用
sort=True,将对uniques进行排序,并打乱codes以保持关系。>>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True) >>> codes array([1, 1, 0, 2, 1]...) >>> uniques array(['a', 'b', 'c'], dtype=object)codes和na_sentinel(默认为-1)中指示缺失值。请注意,缺失值永远不会包含在uniques中。>>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b']) >>> codes array([ 0, -1, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object)到目前为止,我们只分解了列表(内部强制转换为 NumPy 数组)。在分解 pandas 对象时,
uniques的类型会有所不同。对于分类,返回Categorical。>>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques ['a', 'c'] Categories (3, object): ['a', 'b', 'c']请注意,
'b'在uniques.categories中,尽管cat.values中不存在。对于所有其他 pandas 对象,将返回适当类型的索引。
>>> cat = pd.Series(['a', 'a', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques Index(['a', 'c'], dtype='object')如果 NaN 在值中,并且我们希望在值的唯一性中包含 NaN,则可以通过设置
na_sentinel=None来实现。>>> values = np.array([1, 2, 1, np.nan]) >>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1 >>> codes array([ 0, 1, 0, -1]) >>> uniques array([1., 2.])>>> codes, uniques = pd.factorize(values, na_sentinel=None) >>> codes array([0, 1, 0, 2]) >>> uniques array([ 1., 2., nan])
相关用法
- Python pandas.Series.filter用法及代码示例
- Python pandas.Series.first用法及代码示例
- Python pandas.Series.floordiv用法及代码示例
- Python pandas.Series.fillna用法及代码示例
- Python pandas.Series.flags用法及代码示例
- Python pandas.Series.add_prefix用法及代码示例
- Python pandas.Series.map用法及代码示例
- Python pandas.Series.max用法及代码示例
- Python pandas.Series.str.isdecimal用法及代码示例
- Python pandas.Series.str.get用法及代码示例
- Python pandas.Series.to_csv用法及代码示例
- Python pandas.Series.dt.day_name用法及代码示例
- Python pandas.Series.sample用法及代码示例
- Python pandas.Series.head用法及代码示例
- Python pandas.Series.eq用法及代码示例
- Python pandas.Series.plot.line用法及代码示例
- Python pandas.Series.to_pickle用法及代码示例
- Python pandas.Series.between_time用法及代码示例
- Python pandas.Series.reindex_like用法及代码示例
- Python pandas.Series.dt.is_year_end用法及代码示例
注:本文由纯净天空筛选整理自pandas.pydata.org大神的英文原创作品 pandas.Series.factorize。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
