我正在查看fastai库中的一些源代码,函数train_cats
读取如下:
def train_cats(df):
"""Change any columns of strings in a panda's dataframe to a column of
catagorical values. This applies the changes inplace.
for n,c in df.items():
if is_string_dtype(c): df[n] = c.astype('category').cat.as_ordered()
我理解这个功能在做什么,但我不确定as_ordered
部分应该完成什么。
我试着透过documentation on it看,它很稀疏。令我惊讶的是,互联网上关于as_ordered()
的信息也不多。
在这种情况下添加此方法的主要好处是什么?
谢谢。
您应该查看此链接中的排序和订单部分:Pandas Documentation on Categorical。它说:
如果对分类数据进行排序(s.cat.ordered == True),则类别的顺序具有含义,并且可以进行某些操作。如果分类是无序的,.min()/。max()将引发TypeError。
和:
您可以使用as_ordered()或使用as_unordered()无序设置要排序的分类数据。这些将默认返回一个新对象。
我们可以从pandas.Categorical
获得一些信息
s=pd.Series(list('zbdce')).astype('category')
s
0 z
1 b
2 d
3 c
4 e
dtype: category
Categories (5, object): [b, c, d, e, z]
s.cat.as_ordered()
0 z
1 b
2 d
3 c
4 e
dtype: category
Categories (5, object): [b < c < d < e < z]
pd.Categorical(list('zbdce'))
[z, b, d, c, e]
Categories (5, object): [b, c, d, e, z]
pd.Categorical(list('zbdce'),ordered=True)
[z, b, d, c, e]
Categories (5, object): [b < c < d < e < z]
ordered:boolean,(默认为False)此分类是否被视为有序分类。如果为True,将生成结果分类。有序分类方面,在排序时,其类别属性的顺序(反过来又是类别参数,如果提供)。
这是一个辅助函数,它将第一个参数设置为True来调用set_ordered
。
这是set_ordered
:
def set_ordered(self, value, inplace=False):
"""
Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
new_dtype = CategoricalDtype(self.categories, ordered=value)
cat = self if inplace else self.copy()
cat._dtype = new_dtype
if not inplace:
return cat
因此,这只是设置了一个事实,即您希望将您的分类数据视为具有排序。这里有一些更稀疏的文档:https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.api.types.CategoricalDtype.ordered.html
可以在这里找到一些讨论:https://github.com/pandas-dev/pandas/issues/14711