python - 获取 pandas 中分类变量的映射

标签 python pandas

我这样做是为了使分类变量成为数字

>>> df = pd.DataFrame({'x':['good', 'bad', 'good', 'great']}, dtype='category')

       x
0   good
1    bad
2   good
3  great

如何获取原始值和新值之间的映射?

最佳答案

方法1

您可以通过枚举创建字典映射(类似于通过从列表索引创建字典键来从列表创建字典):

dict( enumerate(df['x'].cat.categories ) )

# {0: 'bad', 1: 'good', 2: 'great'}

方法2

或者,您可以映射每一行中的值和代码:

dict( zip( df['x'].cat.codes, df['x'] ) )

# {0: 'bad', 1: 'good', 2: 'great'}

这里发生的事情更加透明,因此可以说更安全。它的效率也低得多,因为 zip() 的参数长度是 len(df)df['x'].cat 的长度.categories 只是唯一值的计数,通常比 len(df) 短得多。

额外讨论

方法 1 有效的原因是类别的类型为 Index:

type( df['x'].cat.categories )

# pandas.core.indexes.base.Index

在这种情况下,您可以像查找列表一样在索引中查找值。

有多种方法可以验证方法 1 是否有效。首先,您可以检查往返是否保留正确的值:

(df['x'] == df['x'].cat.codes.map( dict( 
            enumerate(df['x'].cat.categories) ) ).astype('category')).all()
# True

或者您可以检查方法 1 和方法 2 是否给出相同的答案:

(dict( enumerate(df['x'].cat.categories ) ) == dict( zip( df['x'].cat.codes, df['x'] ) ))

# True

关于python - 获取 pandas 中分类变量的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237567/

相关文章:

python - python中多列的长到宽格式

sql - 具有多列的表中每组的第一个非空值

python - 将 django-mssql 连接到 mssql 服务器(azure)

python - 将一个以小写字母开头的元素连接到列表的前一个元素

python - 使用 Python 按键和小时减少桶

python - Keras 神经网络错误 : Setting an Array Element with a Sequence

python - 不支持的操作数类型 - : 'str' and 'float' when building a bar chart

python - 类型错误 : input expected at most 1 argument, 得到 2

python - 过滤直方图边缘和计数

python - Python 中 'empty' else 语句的必要性