np.where多个变量

时间:2017-08-10 09:37:16

标签: python pandas if-statement case-when np

我有一个数据框:

customer_id [1,2,3,4,5,6,7,8,9,10]
feature1 [0,0,1,1,0,0,1,1,0,0]
feature2 [1,0,1,0,1,0,1,0,1,0]
feature3 [0,0,1,0,0,0,1,0,0,0]

使用这个我想创建一个新变量(比如new_var)来表示当feature 1为1然后new_var = 1,如果feature_2 = 1则new_var = 2,feature3 = 1则new_var = 3 else 4.我是尝试np.where虽然它没有给我一个错误,但它没有做正确的事 - 所以我猜一个嵌套的np.where只能处理一个变量。在这种情况下,在pandas中执行嵌套if / case的最佳方法是什么?

我的np.where代码是这样的:

df[new_var]=np.where(df['feature1']==1,'1', np.where(df['feature2']==1,'2', np.where(df[feature3']==1,'3','4')))

2 个答案:

答案 0 :(得分:1)

我认为您需要numpy.select - 它会选择第一个True值,而所有其他值都不重要:

m1 = df['feature1']==1 
m2 = df['feature2']==1    
m3 = df['feature3']==1 
df['new_var'] = np.select([m1, m2, m3], ['1', '2', '3'], default='4')

<强>示例

customer_id = [1,2,3,4,5,6,7,8,9,10]
feature1 = [0,0,1,1,0,0,1,1,0,0]
feature2 = [1,0,1,0,1,0,1,0,1,0]
feature3  = [0,0,1,0,0,0,1,0,0,0]

df = pd.DataFrame({'customer_id':customer_id,
                   'feature1':feature1,
                   'feature2':feature2,
                   'feature3':feature3})

m1 = df['feature1']==1 
m2 = df['feature2']==1    
m3 = df['feature3']==1 
df['new_var'] = np.select([m1, m2, m3], ['1', '2', '3'], default='4')
print (df)
   customer_id  feature1  feature2  feature3 new_var
0            1         0         1         0       2
1            2         0         0         0       4
2            3         1         1         1       1
3            4         1         0         0       1
4            5         0         1         0       2
5            6         0         0         0       4
6            7         1         1         1       1
7            8         1         0         0       1
8            9         0         1         0       2
9           10         0         0         0       4

如果只有features 10可以将0转换为False而将1转换为True:< / p>

m1 = df['feature1'].astype(bool)
m2 = df['feature2'].astype(bool)
m3 = df['feature3'].astype(bool)
df['new_var'] = np.select([m1, m2, m3], ['1', '2', '3'], default='4')
print (df)
   customer_id  feature1  feature2  feature3 new_var
0            1         0         1         0       2
1            2         0         0         0       4
2            3         1         1         1       1
3            4         1         0         0       1
4            5         0         1         0       2
5            6         0         0         0       4
6            7         1         1         1       1
7            8         1         0         0       1
8            9         0         1         0       2
9           10         0         0         0       4

答案 1 :(得分:0)

<块引用>

试试:

df['new_var']=np.where(df['feature3']==1, '3', '4')
df['new_var']=np.where(df['feature2']==1,'2', df['new_var'])
df['new_var']=np.where(df['feature1']==1, '1', df['new_var'])