有没有一种方法可以比较包含浮点值的数据框的两列,并创建一个新列以基于该列添加标签?

时间:2019-04-24 12:27:09

标签: python pandas dataframe

我有一个如下所示的数据框:

df

            column_A      column_B
0              0.0           0.0                                    
1              0.0           0.0                                    
2              0.0           1.0                                       
3              0.0           0.0                                     
4              0.0           0.0                                     
5              1.0           0.0

我想创建一个if条件,例如:

if(df ['column_A']&df ['column_b'] = 0.0:     df ['label] ='OK' 其他:     df ['label'] ='NO'

我尝试过:

if((0.0 in df['column_A'] ) & (0.0 in df['column_B']))
for index, row in df.iterrows():
  (df[((df['column_A'] == 0.0) & (df['column_B']== 0.0))])

什么都没有给出预期的结果

我希望我的输出是:

            column_A      column_B   label
0              0.0           0.0      OK                          
1              0.0           0.0      OK                            
2              0.0           1.0      NO                               
3              0.0           0.0      OK                             
4              0.0           0.0      OK                             
5              1.0           0.0      NO

2 个答案:

答案 0 :(得分:1)

您可以使用DASH-IF-IOP 4.3来创建一个OKNO的数组,具体取决于条件的结果:

import numpy as np
df['label'] = np.where(df.column_A.add(df.column_B).eq(0), 'OK', 'NO')

     column_A  column_B label
0       0.0       0.0    OK
1       0.0       0.0    OK
2       0.0       1.0    NO
3       0.0       0.0    OK
4       0.0       0.0    OK
5       1.0       0.0    NO

答案 1 :(得分:0)

numpy.whereDataFrame.any一起使用:

#solution if only 1.0, 0.0 values
df['label'] = np.where(df[['column_A', 'column_B']].any(axis=1), 'NO','OK')
#general solution with compare 0
#df['label'] = np.where(df[['column_A', 'column_B']].eq(0).all(axis=1),'OK','NO')

print (df)
   column_A  column_B label
0       0.0       0.0    OK
1       0.0       0.0    OK
2       0.0       1.0    NO
3       0.0       0.0    OK
4       0.0       0.0    OK
5       1.0       0.0    NO