0

I would like to create a new column and assign value for each group (in this case is Color), and in each group:

if Function column is View and Access column is no, the value for the new column will be 'No' for this group;

if Function column = View and Access column = yes, the value for new column will be same as 'Access' for the rows of the group

Data:

Type Color Function Access
A Blue Add yes
A Blue View no
A Red Add no
A Red View yes
B Blue Add yes
B Blue View no

Desired Outcome:

Type Color Function Access New Column
A Blue Add yes no
A Blue View no no
A Red Add no no
A Red View yes yes
B Blue Add yes no
B Blue View no no
# I created a new column first before grouping them
data['New Column'] = ''
data_grouped = data.groupby(['Type', 'Color']

# attempted to loop but stuck here #
for group_name, df_group in data_grouped:
    print(format(group_name))

    for row_index, row in df_group.iterrows():

        if (row['Function'] == 'View') & (row['Access'] == 'no'):
            row['New Column'] = 'no'

        print(col, column_type)
poppp
  • 331
  • 2
  • 3
  • 14
  • 1
    What happens when `df['Function'] == 'Add`? – It_is_Chris Jun 24 '21 at 13:42
  • Hi, if it is df['Function'] == 'Add', it doesn't matter. As long as it is df['Function'] == 'View' and df['Access'] == 'No', the rows for that grouping should be df['New Column'] == 'No'. If df['Function'] == 'View' and df['Access'] == 'Yes', then for each row in that grouping, the new column should be the value from df['Access']. Hope this is clearer. Thank you. – poppp Jun 24 '21 at 13:46

1 Answers1

0

Given that you want a 'no' for all other cases (except from the pair View-Yes), you can do the following:

data['New Column'] = np.where((data['Function']=='View') & (data['Access']=='yes'), 'yes', 'no')
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
  • Hi, thanks, but if data['Function']=='View') & (data['Access']=='yes', data['New Column'] should follow the value from data['Access']. It can be value 'No' if data['Function']=='Add' and access = no for the same group of data['Function']=='View') & (data['Access']=='yes' – poppp Jun 24 '21 at 14:07