user12907213
user12907213

Reputation:

Assign True/False condition based on existing columns

I need to assign a True/False value when a condition is verified. Specifically I have the dataframe

col1      col2    col3   col4   col5    col6   col7    col8   col9
Number1   True   False   True   False   True   False   True   False
Number2   False  False   False  False   False  False   False  False
Number3   True   False   False  False   False  False   False  False
Number4   False  False   False  False   False  True    False  False

I would need to create a new column based on the True/False values. If at least one value is True then assign True in the new column; otherwise, if all values are False, assign False.

From the example above, I should have then:

col1      col2    col3   col4   col5    col6   col7    col8   col9     col10
Number1   True   False   True   False   True   False   True   False    True
Number2   False  False   False  False   False  False   False  False    False
Number3   True   False   False  False   False  False   False  False    True
Number4   False  False   False  False   False  True    False  False    True

I have tried with

if (df['COL1'], df['COL2'], df['COL3'], df['COL4'], df['COL5'], df['COL6'], df['COL7'], df['COL8'], df['COL9']).any():
                df[index,'COL10'] = True
            else:
                df[index,'COL10'] = False

but this assigns all True values.

Could you please help me to get the right output? Many thanks

Upvotes: 3

Views: 948

Answers (2)

Vikas Thamke
Vikas Thamke

Reputation: 11

You have done two wrong things here. One is missed iterating through rows and second is involved col1 in the expression. Here's what I've tried in a similar way that you've tried.

df['col10'] = False
for index, row in df.iterrows():
    if row['col2'] or row['col3'] or row['col4'] or row['col5'] or row['col6'] or row['col7'] or row['col8'] or row['col9']:
        df.iloc[index,9] = True
    else:
        df.iloc[index,9] = False

A single line solution to the question would be:

df['col10'] = df.loc[:,'col2':].any(1)

Upvotes: 0

BENY
BENY

Reputation: 323226

Just do any

df.loc[:,'col2':].any(1)
0     True
1    False
2     True
3     True
dtype: bool

#df['col10']=df.loc[:,'col2':].any(1)

Upvotes: 5

Related Questions