Home > Mobile >  Generate a binary column by searching values in pandas data frame
Generate a binary column by searching values in pandas data frame

Time:06-23

dict1={'TA':{'MA':8.8,'BA':8.8,'CA':1.3,'DA':1.4,'RA':1.5 },
   'GA':{'MA':1.1,'BA':1.2,'CA':8.8,'DA':8.8,'RA':8.8 },
   'RA':{'MA':4.1,'BA':5.2,'CA':4.5,'DA':1.8,'RA':1.2 },
   'SA':{'MA':9.2,'BA':1.1,'CA':1.3,'DA':8.8,'RA':8.8 }}
 df1=pd.DataFrame.from_dict(dict1,orient="index")

I have a data frame

      MA  BA  CA  DA  RA   
  TA 8.8 8.8 1.3 1.4 1.5    
  GA 1.1 1.2 8.8 8.8  8.8   
  RA 4.1 5.2 4.5 8.8  1.2   
  SA 9.2 1.1 1.3 8.8  8.8   
  
  #Expected data_frame in output
     MA  BA  CA  DA  RA   New_Column
  TA 8.8 8.8 1.3 1.4 1.5    1
  GA 1.1 1.2 8.8 8.8  8.8   0
  RA 4.1 5.2 4.5 8.8  1.2   1
  SA 9.2 1.1 1.3 8.8  8.8   1

Is there anyway to generate the New_Column from this above input data frame. If the count of value 8.8 is less than equal to 2 in any row then its value would be 1, otherwise 0.

CodePudding user response:

Does this work:

df['new_column'] = df.apply(lambda x : 1 if sum(x == 8.8) <= 2 else 0, axis = 1)
df

    MA  BA  CA  DA  RA  new_column
TA  8.8 8.8 1.3 1.4 1.5 1
GA  1.1 1.2 8.8 8.8 8.8 0
RA  4.1 5.2 4.5 1.8 1.2 1
SA  9.2 1.1 1.3 8.8 8.8 1
  • Related