提问人:Marius 提问时间:11/14/2014 最后编辑:Marius 更新时间:5/13/2022 访问量:66128
检查数据帧列是否为分类
Check if dataframe column is Categorical
问:
我似乎无法在 v0.15+ 中使用 Pandas 改进的分类进行简单的 dtype 检查。基本上我只想要这样的东西.is_categorical(column) -> True/False
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({
'x': np.linspace(0, 50, 6),
'y': np.linspace(0, 20, 6),
'cat_column': random.sample('abcdef', 6)
})
df['cat_column'] = pd.Categorical(df2['cat_column'])
我们可以看到 for 分类列是 'category':dtype
df.cat_column.dtype
Out[20]: category
通常,我们可以通过与名称进行比较来进行 dtype 检查 的 dtype:
df.x.dtype == 'float64'
Out[21]: True
但是在尝试检查列是否
是绝对的:x
df.x.dtype == 'category'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-94d2608815c4> in <module>()
----> 1 df.x.dtype == 'category'
TypeError: data type "category" not understood
有什么方法可以在 pandas v0.15+ 中进行这些类型的检查吗?
答:
首先,dtype 的字符串表示形式是 和 not ,所以这有效:'category'
'categorical'
In [41]: df.cat_column.dtype == 'category'
Out[41]: True
但实际上,正如你所注意到的,这个比较为其他 dtype 提供了一个,所以你必须用一个块来包装它。TypeError
try .. except ..
使用 pandas 内部检查的其他方法:
In [42]: isinstance(df.cat_column.dtype, pd.api.types.CategoricalDtype)
Out[42]: True
In [43]: pd.api.types.is_categorical_dtype(df.cat_column)
Out[43]: True
对于非分类列,这些语句将返回,而不是引发错误。例如:False
In [44]: pd.api.types.is_categorical_dtype(df.x)
Out[44]: False
对于更旧版本的 ,将上面的代码片段替换为 。pandas
pd.api.types
pd.core.common
评论
np.dtype("int64" == "category"
pandas v2.1.0
isinstance(df.x, pd.CategoricalDtype)
改用该属性进行比较,它应该始终有效,因为它只是一个字符串:name
>>> import numpy as np
>>> arr = np.array([1, 2, 3, 4])
>>> arr.dtype.name
'int64'
>>> import pandas as pd
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat.dtype.name
'category'
因此,总而言之,您最终可以得到一个简单、直接的函数:
def is_categorical(array_like):
return array_like.dtype.name == 'category'
只是把这个放在这里,因为熊猫。DataFrame.select_dtypes()
是我真正想要的:
df['column'].name in df.select_dtypes(include='category').columns
感谢@Jeff。
在我的 pandas 版本 (v1.0.3) 中,可以使用 joris 答案的较短版本。
df = pd.DataFrame({'noncat': [1, 2, 3], 'categ': pd.Categorical(['A', 'B', 'C'])})
print(isinstance(df.noncat.dtype, pd.CategoricalDtype)) # False
print(isinstance(df.categ.dtype, pd.CategoricalDtype)) # True
print(pd.CategoricalDtype.is_dtype(df.noncat)) # False
print(pd.CategoricalDtype.is_dtype(df.categ)) # True
评论
我遇到了这个线程,寻找完全相同的功能,并且还从此处的 pandas 文档中找到了另一种选择。
看起来检查 pandas 数据帧列是否为分类序列的规范方法应如下:
hasattr(column_to_check, 'cat')
因此,根据初始问题中给出的示例,这将是:
hasattr(df.x, 'cat') #True
看看 Tratner @Jeff回答,因为条件不需要被视为 cataegorical 列,
我建议考虑对“categorical_dtypes”列表中的 dtypes 进行分类:df.cat_column.dtype == 'category'
True
def is_cat(column):
categorical_dtypes = ['object', 'category', 'bool']
if column.dtype.name in categorical_dtypes:
return True
else:
return False
´´´
评论
df.select_dtypes(include=['category'])
category
numpy.dtype
numpy
False