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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32633977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:54:10  来源:igfitidea点击:

How to create categorical variable based on a numerical variable

pythonpandasdataframecategorical-data

提问by Klausos Klausos

My DataFrame hase one column:

我的 DataFrame 有一列:

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

How can I add one more column 'col2' that would contain categorical information in reference to col1:

如何再添加一列“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'

采纳答案by YS-L

You could first create a new column col2, and update its values based on the conditions:

您可以先创建一个新列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

Output:

输出:

   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

Alternatively, you can also apply a function based on the column col1:

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

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

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

and this will result in the same output.

这将导致相同的输出。

The applyapproach should be preferred in this case as it is much faster:

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

However, when the size of the DataFrame is large, the built-in vectorized operations (i.e. with the masking approach) might be faster.

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

回答by DontDivideByZero

You could use pd.cutas follows:

你可以使用pd.cut如下:

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

Output:

输出:

   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

回答by EdChum

2 ways, use a couple loccalls to mask the rows where the conditions are met:

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

Or use a nested np.where:

或者使用嵌套的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