如何根据python中另一个变量的事件率将分类变量重新编码为序数?

时间:2016-05-30 00:23:49

标签: python pandas data-manipulation categorical-data

我在python中有一个带有许多分类变量的数据帧,目标变量是二进制的。我想基于目标变量事件率的等级(对于变量的每个类别,与目标变量的平均值相同)将分类变量转换为序数。例如,如果以下是我的原始数据集

enter image description here

对于column1上的每个类别,aka,' A'和' B',我们有: enter image description here

对于第2列的每个类别,又名,' C',' D',' E'' F',&#39 ; G',我们有:

enter image description here

所以我希望能够像这样创建最终数据集:

enter image description here

我怎样才能创建这样的?

感谢!!!!

2 个答案:

答案 0 :(得分:0)

只需计算每个mean类别值grouped,结果rank和类别值map。示例数据用于说明:

import string
abc = string.ascii_uppercase
df = pd.DataFrame({'target': np.random.randint(low=0, high=2, size=10), 'col1': np.random.choice(list(abc[:2]), size=10), 'col2': np.random.choice(list(abc[:5]), size=10)})

  col1 col2  target
0    B    B       0
1    A    E       0
2    B    A       1
3    B    E       1
4    A    A       0
5    A    E       0
6    B    D       1
7    A    E       0
8    A    E       1
9    B    B       0

沿着上面的代码生成两列:

for col in ['col1', 'col2']:
    df[col] = df.loc[:, col].map(df.groupby(col).target.mean().rank().astype(int))

   col1  col2  target
0     2     1       0
1     1     2       0
2     2     3       1
3     2     2       1
4     1     3       0
5     1     2       0
6     2     4       1
7     1     2       0
8     1     2       1
9     2     1       0

答案 1 :(得分:0)

你想要做的是transform。让我们看看以下......

col1 col2  target
0    A    D       1
1    A    A       0
2    A    E       0
3    B    A       0
4    A    C       0
5    A    D       1
6    B    E       0
7    A    C       0
8    B    C       0
9    B    B       0

您可以使用groupby进行转换:

df.groupby('col1').transform(np.mean)

     target
0  0.333333
1  0.333333
2  0.333333
3  0.000000
4  0.333333
5  0.333333
6  0.000000
7  0.333333
8  0.000000
9  0.000000

现在,您只需要转换的系列信息......

df.groupby('col1').transform(np.mean)['target']
0    0.333333
1    0.333333
2    0.333333
3    0.000000
4    0.333333
5    0.333333
6    0.000000
7    0.333333
8    0.000000
9    0.000000

pd.Series可以通过几种不同的方式转换为因子。一种方法是使用pd.factorize()

pd.factorize(df.groupby('col1').transform(np.mean)['target'])
(array([0, 0, 0, 1, 0, 0, 1, 0, 1, 1]),
 Float64Index([0.333333333333, 0.0], dtype='float64'))

其中您只查找因子值:

pd.factorize(df.groupby('col1').transform(np.mean)['target'])[0]
array([0, 0, 0, 1, 0, 0, 1, 0, 1, 1])

现在,只需为其指定您选择的列名称:)。

希望这会有所帮助......