使用 pandas 将分类变量转换为整数

MAS*_*MAS 2 python python-2.7 pandas

我正在尝试将分类变量转换为整数。但是,我希望他们使用相同的键(A 在所有字段中都转换为 1。我下面的代码不使用相同的键。

import pandas as pd

df1 = pd.DataFrame({'A' : ['A', 'A', 'C', 'D','B']})

df2 = pd.DataFrame({'A' : ['D', 'D', 'B', 'A','A']})

df1_int = pd.factorize(df1['A'])[0]
print df1_int

df2_int = pd.factorize(df2['A'])[0]
print df2_int
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

    [0 0 1 2 3]
    [0 0 1 2 2]
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 5

您可以将现有列转换为分类 dtype,并且当您对两者使用相同的类别时,基础整数值(您可以作为codesthrough访问Series.cat.codes)将在两个数据帧之间保持一致:

In [5]: df1['A'].astype('category', categories=list('ABCD')).cat.codes
Out[5]:
0    0
1    0
2    2
3    3
4    1
dtype: int8

In [6]: df2['A'].astype('category', categories=list('ABCD')).cat.codes
Out[6]:
0    3
1    3
2    1
3    0
4    0
dtype: int8
Run Code Online (Sandbox Code Playgroud)

如果您不想手动指定类别,您还可以将第一个数据帧的类别重用于第二个以确保它们相同:

df1['A'] = df1['A'].astype('category')
df2['A'] = df2['A'].astype('category', categories=df1['A'].cat.categories)
Run Code Online (Sandbox Code Playgroud)

注意:astype('category', categories=...)仅适用于熊猫 >= 0.16,对于熊猫 0.15,您可以先将其转换为类别 dtype,然后使用set_categories(参见docs)设置类别。