【问题标题】:Difference between pandas Series category data type vs pandas Categorical data type熊猫系列类别数据类型与熊猫分类数据类型之间的区别
【发布时间】:2019-01-17 03:40:16
【问题描述】:

我遇到了这种令人惊讶的无法访问我期望的 CSV 中的一列数据的 codes 属性的问题@。

如果我运行以下代码

import pandas

csv_str = """c1,c2
a,1
b,2
a,3
c,4
a,5"""

df = pandas.read_csv( pandas.compat.StringIO( csv_str ) , dtype={'c1':'category'} )

print( "DataFrame\n{}".format( df ))
print( "\nDataTypes\n{}".format( df.dtypes ))
print( "\nDataCodes\n{}".format( pandas.Categorical( df['c1'] ).codes ))

# EXCEPTION
print( df['c1'].codes )

我得到以下控制台输出

DataFrame
  c1  c2
0  a   1
1  b   2
2  a   3
3  c   4
4  a   5

DataTypes
c1    category
c2       int64
dtype: object

DataCodes
[0 1 0 2 0]
Traceback (most recent call last):
  File "/Users/$USER/test.py", line 17, in <module>
    print( df['c1'].codes )
  File "/Users/$USER/Applications_User/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 4376, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'codes'

这里到底发生了什么,为什么我不能将属于类别类型的 c1 列视为 Categorical?我想我在这里遗漏了一些微妙的观点。 pandas category 值 Series 与 pandas Categorical 数据类型有什么区别。

是否有直接访问类别值系列代码的替代途径?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    pd.Categorical 返回一个Categorical 类型的对象:

    c = pd.Categorical(df['c1'])
    c
    # [a, b, a, c, a]
    # Categories (3, object): [a, b, c]
    
    type(c)
    pandas.core.arrays.categorical.Categorical
    

    OTOH,df['c1']Series 类型的 categorical。这意味着它的分类属性和功能必须通过.cat accessor 访问。

    type(df['c1'])
    # pandas.core.series.Series
    
    df['c1'].cat.codes
    
    0    0
    1    1
    2    0
    3    2
    4    0
    dtype: int8
    

    【讨论】:

    • 漂亮,不要与pandas.Series.str.cat 混淆。
    猜你喜欢
    • 2018-03-17
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2018-06-27
    相关资源
    最近更新 更多