如何在数据框中获取新列应用逻辑运算符,if else else if

时间:2016-08-07 10:19:50

标签: python pandas filter

Feature1, Feature2, Feature3, Feature4, TARGET

5.1,3.5,1.4,0.2,Iris-setosa    
4.9,3.0,1.4,0.2,Iris-setosa        
6.4,3.2,4.5,1.5,Iris-versicolor    
6.9,3.1,4.9,1.5,Iris-versicolor   
6.3,2.5,5.0,1.9,Iris-virginica    
6.5,3.0,5.2,2.0,Iris-virginica    

如何使用if else if或逻辑运算符从特征关系中计算目标(种类)?例如

如果feature 1< 5.2和feature 2> 3.4和feature 3< 1.5和feature 4< .3
然后打印iris-setosa

2 个答案:

答案 0 :(得分:1)

您可以使用loc根据所需的TARGET列对数据框进行分组,如下所示:

In [4]: mask = (df['Feature1'] < 5.2) & (df['Feature2'] > 3.4)                 \
   ...:        & (df['Feature3'] < 1.5) & (df['Feature4'] < .3)

In [5]: df.loc[mask, "TARGET"]
Out[5]: 
0    Iris-setosa    
Name: TARGET, dtype: object

答案 1 :(得分:0)

试试这个:使用np.where(cond,if true,if false)

df['new'] = np.where((df['Feature1'] < 5.2) & (df['Feature2'] > 3.4) & (df['Feature3'] < 1.5) & (df['Feature4'] < .3), "iris-setosa", "")