亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

pd.Series.cat.as_ordered() 在 Pandas 中做什么?

pd.Series.cat.as_ordered() 在 Pandas 中做什么?

幕布斯6054654 2021-12-09 10:54:44
我在看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部分應該完成什么。我試著查看它的文檔,它很稀疏。令我驚訝的是as_ordered(),互聯網上的信息也不多。在這種情況下添加此方法的主要好處是什么?
查看完整描述

3 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

您應該查看此鏈接中的排序和順序部分:Pandas Documentation on Categorical。它說:

如果分類數據是有序的(s.cat.ordered == True),那么分類的順序就有意義并且某些操作是可能的。如果分類是無序的,.min()/.max() 將引發 TypeError。

和:

您可以將分類數據設置為使用 as_ordered() 進行排序或使用 as_unordered() 進行無序排序。默認情況下,這些將返回一個新對象。


查看完整回答
反對 回復 2021-12-09
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

這是一個輔助函數,調用set_ordered時第一個參數設置為 True。


這是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


查看完整回答
反對 回復 2021-12-09
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

我們可以從 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, (default False) 此分類是否被視為有序分類。如果為 True,則會對結果分類進行排序。有序分類在排序時尊重其類別屬性的順序(如果提供,則反過來是類別參數)。


查看完整回答
反對 回復 2021-12-09
  • 3 回答
  • 0 關注
  • 495 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號