给定分类数据的现有代码/标签映射,我想将一系列数据框转换为分类数据。我正在努力将一个包含(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(似乎不是这样),是实际的系列(不是吗? ,因为这样可以允许重复))?它似乎只保留实际的代码标签映射,但是我不确定如何使用它(即将其应用于已经存在的系列)。
如果我对您的理解正确,则可以通过使用其属性将其转换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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句