我遇到了这种令人惊讶的无法访问我期望的 CSV 中一列数据的codes
属性,我正在通过 dtype
参数强制到类别类型以read_csv
。
如果我运行以下代码
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( "DataFramen{}".format( df ))
print( "nDataTypesn{}".format( df.dtypes ))
print( "nDataCodesn{}".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 列视为分类?我想我在这里错过了一些微妙的点。熊猫类别值系列与熊猫分类数据类型有什么区别。
是否有直接访问类别值系列代码的替代途径?
> 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']
是categorical
型Series
。这意味着必须通过.cat
访问器访问其分类属性和函数。
type(df['c1'])
# pandas.core.series.Series
df['c1'].cat.codes
0 0
1 1
2 0
3 2
4 0
dtype: int8