title: How do I make a field dynamically populated using a loop based on other fields in python?
body: <p>My data field names consists of letter number combinations that looks something like this.</p>
  <pre><code>A1 | A2 | A3 | A4 | B1 | B2 | B3 | B4 | C1 | C2 | C3 | C4
  0  | 0  | 0  | 1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0
  0  | 0  | 0  | 0  | 0  | 0  | 1  | 0  | 0  | 1  | 0  | 0
  </code></pre>
  <p>There will always be the same number of header fields within each letter. So in the above, if there were a &quot;D&quot; field, there would be D1 D2 D3 D4... The same would apply to the number, if it went up to 5 then all the letters would be up to 5. Each letter field group can only have a 1 in one of the field positions.</p>
  <p>I would like create an additional column for each letter that indicates which header number the 1 appears in. So in the above example I would like to have the following fields added</p>
  <pre><code>A1 | A2 | A3 | A4 | B1 | B2 | B3 | B4 | C1 | C2 | C3 | C4 | Cat_A | Cat_B | Cat_C
  0  | 0  | 0  | 1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0  |   4   |   1   |  0
  0  | 1  | 0  | 0  | 0  | 0  | 1  | 0  | 0  | 1  | 0  | 0  |   2   |   3   |  2
  </code></pre>
  <pre><code># X_cols captures all the fields that have a letter and number in the event there are other fields I want to ignore
  X = df.filter(regex='^[a-zA-Z][0-9]') 
  X_cols = X.columns.tolist()
  
  # element_count captures the largest number for each letter category to be used in a loop
  # Categories captures all the unique letters in the fields
  element_count = pd.to_numeric(X.columns.str[1].max()) 
  categories = X.columns.str[0].unique()
  
  # Original thinking is to create a loop that basically replicates each field but only puts in the numerical value for the 1 position. So Cat_A4 would get a 4 and A1,A2,A3 would be blank. I would then collapse all the letter fields into single letter fields using sum. So Cat_A would be the sum of A1-A4 and so one for each letter category.
  
  # this is the current loop but doesn't do what I want
  for cat in categories:
      col_list=[]
      for element in range(1,element_count+1):
          col_list.append(f'{cat}{element}')
          df[f'cat_{cat}{element}'] = df[f'{cat}{element}'].apply(lambda x: element if x==1 else '')
          df[f'cat_{cat}'] = df[col_list].sum(axis=1)
  </code></pre>
  <p>Any help to solve this would be great. It does not have to be my approach to get to the final result which is simply a single new field for each category letter indicating where the &quot;1&quot; appeared</p>