Manu Sharma
Manu Sharma

Reputation: 1739

Numpy logical conditions for labeling the data

I am trying to create another label column which is based on multiple conditions in my existing data

df

ind group people value value_50 val_minmax
 1     1    5    100    1        10
 1     2    2    90     1        na
 2     1    10   80     1        80
 2     2    20   40     0        na
 3     1    7    10     0        10
 3     2    23   30     0        na

import pandas as pd 
import numpy as np 

df = pd.read_clipboard()

Then trying to put label on rows as per below conditions

df['label'] = np.where(np.logical_and(df.group == 2, df.value_50 == 1, df.value > 50), 1, 0)

but it is giving me an error

TypeError: return arrays must be of ArrayType

How to perform it in python?

Upvotes: 0

Views: 159

Answers (1)

jezrael
jezrael

Reputation: 862511

Use & between masks:

df['label'] = np.where((df.group == 2) & (df.value_50 == 1) & (df.value > 50), 1, 0)

Alternative:

df['label'] = ((df.group == 2) & (df.value_50 == 1) & (df.value > 50)).astype(int)

Your solution should working if use reduce with list of boolean masks:

mask = np.logical_and.reduce([df.group == 2, df.value_50 == 1, df.value > 50])
df['label'] = np.where(mask, 1, 0)
#alternative
#df['label'] = mask.astype(int)

Upvotes: 2

Related Questions