Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine 2 Boolean columns in pandas

I have a table with few flag columns.(3 agencies rated bank; all cases mutually exclusive => at one time only one flag was ON. If flag1 has a value, flag2 and flag3 wont have any value and so on)

  BankName     Flag1       Flag2    Flag3  
    B1         TRUE         
    B2                                FALSE
    B3                      TRUE
    B4          FALSE  
    B5                       TRUE 

and so on.

What I want:

  BankName     Flag1       Flag2    Flag3   Anyflag  
    B1         TRUE                           TRUE 
    B2                               FALSE    FALSE
    B3                      TRUE              TRUE
    B4          FALSE                         FALSE   
    B5                       TRUE             TRUE

Basically I wish to combine the flags overall in a separate column. I have tried merge, concat and they dont seem to work on boolean columns.

Tried:

[IN]:
df['Any flag']=pd.concat(df['Flag1'], df['Flag2'], df['Flag3'])
[OUT]
TypeError: first argument must be an iterable of pandas objects, you 
passed an object of type "Series"
[IN]:
df['Any flag']=pd.concat(df['Flag1'], df['Flag2'], df['Flag3'], axis=0)
[OUT]
TypeError: concat() got multiple values for argument 'axis'

Please help.

like image 362
noob Avatar asked Oct 19 '25 04:10

noob


1 Answers

Use any(axis='columns')

Ex:

data = [ ['B1', True, '', ''],
 ['B2', '', '', False],
 ['B3', '', True, ''],
 ['B4', False, '', ''],
 ['B5','', True, '']]

df = pd.DataFrame(data, columns=['BankName', 'Flag1', 'Flag2', 'Flag3'])
df["Anyflag"] = df[['Flag1', 'Flag2', 'Flag3']].any(axis='columns')
print(df)

Output:

  BankName  Flag1 Flag2  Flag3  Anyflag
0       B1   True                  True
1       B2               False    False
2       B3         True            True
3       B4  False                 False
4       B5         True            True
like image 110
Rakesh Avatar answered Oct 20 '25 19:10

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!