如何使用一行代码查看所有分类列及其信息?

2024-05-17 22:47:32 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种快速的方法来代替逐列检查唯一的分类列信息

df.columnA.unique()
df.columnB.unique()

如果我想检查超过100的列,我上面键入的代码是不经济的


Tags: 方法代码信息df键入分类经济unique
2条回答
for col in df.columns:
if df[col].dtype == 'object':
    print('\nColumn Name:', col,)
    print(df[col].value_counts())

我自己找到了解决办法

通过^{}选择分类列。然后使用^{}

cat_cols = df.select_dtypes(include='category').columns
res = {col: df[col].cat.categories for col in cat_cols}

这假设所有类别都用于任何给定序列。如果不是这样,可以使用^{}

res = {col: df[col].unique() for col in cat_cols}

行为上的差异是documented

Note: The result of unique() is not always the same as Series.cat.categories, because Series.unique() has a couple of guarantees, namely that it returns categories in the order of appearance, and it only includes values that are actually present.

相关问题 更多 >