简体   繁体   English

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

[英]How to create categorical variable based on a numerical variable

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'

You could use pd.cut as 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

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 apply approach 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 (ie with the masking approach) might be faster.但是,当 DataFrame 的大小很大时,内置的矢量化操作(即使用掩码方法)可能会更快。

2 ways, use a couple loc calls 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将dtype分类变量转换为数值? - How to convert dtype categorical variable to numerical? 无法在具有其他数值和分类变量的数据集中创建基于时间的要素 - Unable to create time-based features in a dataset which has other numerical and categorical variable 数值变量和分类变量之间的百分比 - Percentage between a numerical and categorical variable 如何在不增加数据大小的情况下将大熊猫中的分类变量转换为数值? - How to convert categorical variable to numerical in pandas without increasing size of data? 如果变量全部包含数字,如何知道该变量是分类变量还是数字变量? - How to know if the Variable is Categorical or Numerical if all it contains is Digits? 我想在 Python 中将分类变量转换为数值 - I want to convert the categorical variable to numerical in Python pandas 数据帧中的单独数字和分类变量 - separate numerical and categorical variable in pandas datframe 唯一键-客户ID,分类变量还是数字变量? - Unique Key - CustomerID, A Categorical or a Numerical Variable? plot如何根据plotly中的分类变量分 - How plot points based on categorical variable in plotly 将带有 % 符号的分类变量转换为数值变量 Python Pandas - Converting Categorical Variable with % Sign to Numerical Variable Python Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM