2

I have a dataframe like this:

       df 
          
            A   B   C   D   E
            1   0   1   0   1
            1   1   1   1   0
            0   1   1   1   1
            0   0   1   1   1
            1   1   0   1   1
            1   0   1   1   1
            1   1   0   0   1
            1   0   1   0   0
            1   1   0   0   0
            1   0   0   0   0

So I want to create an output ( as 1) from these columns if both A & B are 1 or if any C/D/E are 1 otherwise the output is zero. However, that not a problem, as I did that using:

         df['Out'] = (df.A & df.B) | df.C | df.D |df.E

So the output was :

       df 


        A   B   C   D   E   Out
        1   0   1   0   1   1
        1   1   1   1   0   1
        0   1   1   1   1   1
        0   0   1   1   1   1
        1   1   0   1   1   1
        1   0   1   1   1   1
        1   1   0   0   1   1
        1   0   1   0   0   1
        1   1   0   0   0   1
        1   0   0   0   0   0

However, the issue is that this logic is fine, but since I pull the data from a DB it is many times possible that the data may be missing any of the columns ( A or B or C or D or E). The logic is the same irrespective.

So if any of A or B is there (assuming 1 is missing- say A) then:

        df['Out'] = (df.B) | df.C | df.D |df.E

If both A & B are missing then:

        df['Out'] = dfB.C | df.D |df.E

If say ( A & C are missing) then:

       df['Out'] = (df.B)| df.D |df.E

If say (A, C, D are missing) , then:

      df['Out'] = (df.B) |df.E

If say (C, D, E are missing), then

       df['Out'] = (df.A & df.B) 

and so on:

So the issue I am facing is that how to write this code in a pythonic way instead of using multiple if statements etc? Any help will me immensely appreciated. Thanks

Stan
  • 786
  • 1
  • 9
  • 25

1 Answers1

4

One idea is add all columns which missing by DataFrame.reindex before test:

df = df.reindex(['A','B','C','D','E'], axis=1, fill_value=0)

df['Out'] = (df.A & df.B) | df.C | df.D | df.E
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252