如何基于数值变量创建分类变量

How to create categorical variable based on a numerical variable

我的 DataFrame 有一列:

import pandas as pd
list=[1,1,4,5,6,6,30,20,80,90]
df=pd.DataFrame({'col1':list})

我如何再添加一列 'col2' 以包含参考 col1:

的分类信息
if col1 > 0 and col1 <= 10 then col2 = 'xxx'
if col1 > 10 and col1 <= 50 then col2 = 'yyy'
if col1 > 50 then col2 = 'zzz'

您可以先创建一个新列 col2,然后根据以下条件更新其值:

df['col2'] = 'zzz'
df.loc[(df['col1'] > 0) & (df['col1'] <= 10), 'col2'] = 'xxx'
df.loc[(df['col1'] > 10) & (df['col1'] <= 50), 'col2'] = 'yyy'
print df

输出:

   col1 col2
0     1  xxx
1     1  xxx
2     4  xxx
3     5  xxx
4     6  xxx
5     6  xxx
6    30  yyy
7    20  yyy
8    80  zzz
9    90  zzz

或者,您也可以应用基于列的函数 col1:

def func(x):
    if 0 < x <= 10:
        return 'xxx'
    elif 10 < x <= 50:
        return 'yyy'
    return 'zzz'

df['col2'] = df['col1'].apply(func)

这将导致相同的输出。

在这种情况下应该首选 apply 方法,因为它要快得多:

%timeit run() # packaged to run the first approach
# 100 loops, best of 3: 3.28 ms per loop
%timeit df['col2'] = df['col1'].apply(func)
# 10000 loops, best of 3: 187 µs per loop

但是,当 DataFrame 的大小很大时,内置的矢量化操作(即使用掩码方法)可能会更快。

2 种方法,使用一对 loc 调用来屏蔽满足条件的行:

In [309]:
df.loc[(df['col1'] > 0) & (df['col1']<= 10), 'col2'] = 'xxx'
df.loc[(df['col1'] > 10) & (df['col1']<= 50), 'col2'] = 'yyy'
df.loc[df['col1'] > 50, 'col2'] = 'zzz'
df

Out[309]:
   col1 col2
0     1  xxx
1     1  xxx
2     4  xxx
3     5  xxx
4     6  xxx
5     6  xxx
6    30  yyy
7    20  yyy
8    80  zzz
9    90  zzz

或使用嵌套 np.where:

In [310]:
df['col2'] = np.where((df['col1'] > 0) & (df['col1']<= 10), 'xxx', np.where((df['col1'] > 10) & (df['col1']<= 50), 'yyy', 'zzz'))
df

Out[310]:
   col1 col2
0     1  xxx
1     1  xxx
2     4  xxx
3     5  xxx
4     6  xxx
5     6  xxx
6    30  yyy
7    20  yyy
8    80  zzz
9    90  zzz

您可以按如下方式使用 pd.cut

df['col2'] = pd.cut(df['col1'], bins=[0, 10, 50, float('Inf')], labels=['xxx', 'yyy', 'zzz'])

输出:

   col1 col2
0     1  xxx
1     1  xxx
2     4  xxx
3     5  xxx
4     6  xxx
5     6  xxx
6    30  yyy
7    20  yyy
8    80  zzz
9    90  zzz