首页 > 解决方案 > 无法解释“CategoricalDtype”

问题描述

我想将变量分成不同的类型。例如:

Tweets   ID    Registration Date   num_unique_words   photo_profile  range
object  int64  object              float64             int64         category       

我所做的是:

type_dct = {str(k): list(v) for k, v in df.groupby(df.dtypes, axis=1)}但我有一个 TypeError:

TypeError: Cannot interpret 'CategoricalDtype(categories=['<5',
 '>=5'], ordered=True)' as a data type

range可以取两个值:'<5' 和 '>=5'。

我希望你能帮助处理这个错误。

df = pd.DataFrame({'Tweets': ['Tweet 1 from user 1', 'Tweet 2 from user 1', 
                              'Tweet 1 from user 3', 'Tweet 10 from user 1'], 
                   'ID': [124, 124, 12, 124], 
                   'Registration Date': ['2020-12-02', '2020-11-21', 
                                         '2020-12-02', '2020-12-02'], 
                   'num_unique_words': [41, 42, 12, 69], 
                   'photo_profile': [1, 0, 1, 1], 
                   'range': ['<5', '<5', '>=5', '<5']}, 
                  index=['falcon', 'dog', 'spider', 'fish'])

标签: pythonpandascategorical-data

解决方案


更新:

这比我想象的要复杂得多,但这里有一个使用列表理解的解决方法:

type_dct = {str(k): list(v) for k, v in df.groupby([i.name for i in df.dtypes], axis=1)}

输出:

{'category': ['range'],
 'int64': ['ID', 'num_unique_words', 'photo_profile'],
 'object': ['Tweets', 'Registration Date']}

pd.CategorialDtypes 本身在 groupby 中不能很好地工作,我们必须使用该对象的 name 属性。


采用pd.DataFrame.select_dtypes

来自文档的示例。

df = pd.DataFrame({'a': [1, 2] * 3,
                   'b': [True, False] * 3,
                   'c': [1.0, 2.0] * 3})
df
        a      b  c
0       1   True  1.0
1       2  False  2.0
2       1   True  1.0
3       2  False  2.0
4       1   True  1.0
5       2  False  2.0
df.select_dtypes(include='bool')
   b
0  True
1  False
2  True
3  False
4  True
5  False
df.select_dtypes(include=['float64'])
   c
0  1.0
1  2.0
2  1.0
3  2.0
4  1.0
5  2.0
df.select_dtypes(exclude=['int64'])
       b    c
0   True  1.0
1  False  2.0
2   True  1.0
3  False  2.0
4   True  1.0
5  False  2.0

推荐阅读