pandas DataFrame将代码或标签转换为分类

问题描述 投票:0回答:1

考虑到分类数据的现有代码/标签映射,我想将一系列数据框转换为分类数据。我正在努力转换一个包含(a)标签为分类的序列和包含(b)代码为分类的序列。

系列数据包含代码(而不是类别标签,该代码与找到的许多示例不同)。

这是我到目前为止所得到的:

# this is the code-label mapping that I'd like to apply for the
# (a) label -> cat conversion (`df1`)
# (b) code -> cat conversion (`df2`)

>>> cat = pd.Categorical.from_codes([-1, 1, 2, 3], ['-', 'a', 'b', 'c'])
>>> cat.codes
array([-1,  1,  2,  3], dtype=int8)
>>> cat
[NaN, a, b, c]
Categories (4, object): [-, a, b, c]
>>> cat.__array__
<bound method Categorical.__array__ of [NaN, a, b, c]
Categories (4, object): [-, a, b, c]>


>>> df1
   x
0  a
1  a
2  c
3  b
4  b
>>> df2
   y
0  nan
1  1
2  3
3  2
4  2

我将如何将x转换为使用cat作为类型。我认为我的问题是我不太了解pd.Categorical的实际含义或使用意图(是dtype(似乎不是这样),是实际的系列(不是)看起来还是这样,因为那样就可以重复))?它似乎只保留实际的代码标签映射,但是我不确定如何使用它(即,将其应用于已经存在的系列)。

python pandas categories categorical-data
1个回答
0
投票

如果我对您的理解正确,可以通过在df1.x属性上使用cat.astype转换为_dtype的类别

df1.x.astype(cat._dtype)

Out[950]:
0    a
1    a
2    c
3    b
4    b
Name: x, dtype: category
Categories (4, object): [-, a, b, c]
© www.soinside.com 2019 - 2024. All rights reserved.