Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have a data frame:

  dog1  dog2  cat1  cat2  ant1  ant2

0    1     2     3     4     5     6

1    1     2     3     4     0     0

2    3     3     3     3     3     3

3    4     3     2     1     1     0

I want to add a new column based on the following conditions:

 if   max(dog1, dog2) > max(cat1, cat2) > max(ant1, ant2) ----->   2

 elif max(dog1, dog2) > max(cat1, cat2)                   ----->   1

 elif max(dog1, dog2) < max(cat1, cat2) < max(ant1, ant2) ----->  -2

 elif max(dog1, dog2) < max(cat1, cat2)                   ----->  -1

 else                                                     ----->   0

So it should become this:

  dog1  dog2  cat1  cat2  ant1  ant2   new

0    1     2     3     4     5     6    -2

1    1     2     3     4     0     0    -1

2    3     3     3     3     3     3     0

3    4     3     2     1     1     0     2     

I know how to do it with straightforward conditions.

1 Answer

0 votes
by (36.8k points)

You can use .max(axis=1) function in pandas for it:

conditions = [

       (df[['dog1','dog2']].max(axis=1) > df[['cat1','cat2']].max(axis=1)) & (df[['cat1','cat2']].max(axis=1) > df[['ant1','ant2']].max(axis=1)), 

       (df[['dog1','dog2']].max(axis=1) > df[['cat1','cat2']].max(axis=1)),

       (df[['dog1','dog2']].max(axis=1) < df[['cat1','cat2']].max(axis=1)) & (df[['cat1','cat2']].max(axis=1) < df[['ant1','ant2']].max(axis=1)), 

       (df[['dog1','dog2']].max(axis=1) < df[['cat1','cat2']].max(axis=1))]

choices = [2,1,-2,-1]

df['new'] = np.select(conditions, choices, default=0)

output:

   dog1  dog2  cat1  cat2  ant1  ant2  new

0     1     2     3     4     5     6   -2

1     1     2     3     4     0     0   -1

2     3     3     3     3     3     3    0

3     4     3     2     1     1     0    2

Improve your knowledge in data science from scratch using Data science online courses 

Browse Categories

...