如何计算熊猫的分类特征数量?

Kry*_*tof 6 pandas categorical-data dtype

我有一个pd.DataFrame包含不同的dtypes列。我想要每种类型的列数。我使用Pandas 0.24.2。

我试过了:

    dataframe.dtypes.value_counts()
Run Code Online (Sandbox Code Playgroud)

出于其他dtypes (float64, object, int64)原因,它工作正常,但出于一个奇怪的原因,它没有汇总“类别”功能,因此每个类别的计数都不同(好像它们将被视为dtypes的不同值)。

我也尝试过:

    dataframe.dtypes.groupby(by=dataframe.dtypes).agg(['count'])
Run Code Online (Sandbox Code Playgroud)

但这引起了

TypeError:无法理解的数据类型。

可复制示例:

import pandas as pd

df = pd.DataFrame([['A','a',1,10], ['B','b',2,20], ['C','c',3,30]], columns = ['col_1','col_2','col_3','col_4'])

df['col_1'] = df['col_1'].astype('category')
df['col_2'] = df['col_2'].astype('category')

print(df.dtypes.value_counts())
Run Code Online (Sandbox Code Playgroud)

预期结果:

    int64       2
    category    2
    dtype: int64
Run Code Online (Sandbox Code Playgroud)

实际结果:

    int64       2
    category    1
    category    1
    dtype: int64
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

使用DataFrame.get_dtype_counts

print (df.get_dtype_counts())
category    2
int64       2
dtype: int64
Run Code Online (Sandbox Code Playgroud)

但如果使用最新版本的 pandas,建议使用您的解决方案:

自版本 0.25.0 起已弃用。

使用 .dtypes.value_counts() 代替。


U10*_*ard 5

正如@jezrael 提到它在 0.25.0 中被弃用,dtypes.value_counts(0)会给出两个ie category,所以要修复它:

print(df.dtypes.astype(str).value_counts())
Run Code Online (Sandbox Code Playgroud)

输出:

int64       2
category    2
dtype: int64
Run Code Online (Sandbox Code Playgroud)