Home > Blockchain >  IF AND Statements
IF AND Statements

Time:05-30

I have a 'Current Result' in the form of a data frame in Python (depicting in Excel as an illustration).

I'd like to add a column that classifies whether a row is a 'PRIME' or an 'ALT' designation.

The rules for whether something is a 'ALT' is both of the following:

  • 'Group' column is not 'NaN'
  • AND
  • 'Utilization' is always 0

enter image description here

Is a nested IF / AND statement the only concept that will work or is there a more efficient way to do this? PS I am newer to Python.

ADDING EXAMPLE CODE OF A DATA FRAME:

import pandas as pd
 
### Generate data from lists.
data = {'Part':['AAA', 'BBB', 'CCC', 'DDD','EEE','FFF','GGG', 'HHH', 'III', 'JJJ', 'LLL','MMM','NNN'], 'Group':['', '', '', '','','45','45', '45', '', 'FF', 'FF','7J','7J'], 'Utl':['0', '0', '0', '0','0','100','0', '0', '0', '100', '0','100','0']}
 
### Create DataFrame
df = pd.DataFrame(data)
 
### Print the output.
print(df)

CodePudding user response:

Its kind of hard to re-create without digestible data, but I believe this will get you what you need IIUC

data = {
    'Group' : [np.nan, None, np.nan, '7f', '7f', '7f', None, None, None, '4j', '4j', None, None, '4j'],
    'Utilization':[0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 100, 0, 0, 99]
}
df = pd.DataFrame(data)
#This is here just in case you have some np.nan's instead of None it'll make everything the same
df['Group'] = df['Group'].replace({np.nan : None})
condition_list = [
    (df['Group'].values == None) | ((df['Utilization']%2 == 0) & (df['Utilization'] > 0)), 
    (df['Group'].values != None) & (df['Utilization']%2 != 0) & (df['Utilization'] > 0),
    (df['Group'].values != None) & (df['Utilization'] == 0)
]
choice_list = ['Prime', 'Alt', 'Alt']
df['Check'] = np.select(condition_list, choice_list, 0)
df
  • Related