title: How do I copy a Python DataFrame conditionally to columns named partly in cells?
body: <p>How does one select rows to change values on one column based on the contents of another column, and use the value in a cell of the selected rows to choose the column to fill?</p>
  
  <p>I'm new to Python and not sure how to do things in a Pythonesque way. I've got a few columns from a data source that I am trying to munge into a different format.</p>
  
  <p>For example, in the following, for rows where ProvincePolled=='Ontario', I would like to copy the CandidateA column content to 'Ontario CandidateA', and the CandidateB column content to 'Ontario CandidateB'. </p>
  
  <p>And for the BC and Quebec rows, I would similarly like to copy over the values for the CandidateA and CandidateB columns to the columns named by concatenating the ProvincePolled cell and the names of those columns. </p>
  
  <p>Finally, the rows where ProvincePolled=='Canada' will need to have the CandidateY column results copied to the respective 'ProvinceX CandidateY' columns (where ProvinceX in (Ontario, BC, Quebec) and Y in ('A','B').</p>
  
  <pre><code>  df = pd.DataFrame({'ProvincePolled':['Ontario','Ontario','BC','Quebec','Canada'],
                    'CandidateA':[33.1,31.3,27.7,33.3,30.0],
                    'CandidateB':[12.1,15.3,28.7,11.3,18.0],
                    'Ontario CandidateA':[0.0,0,0,0,0],
                    'Ontario CandidateB':[0.,0,0,0,0],
                    'BC CandidateA':[0.,0,0,0,0],
                    'BC CandidateB':[0.,0,0,0,0],
                    'Quebec CandidateA':[0.,0,0,0,0],
                    'Quebec CandidateB':[0.,0,0,0,0],
                    })
  df
  </code></pre>
  
  <p>Sorry about the formatting here:</p>
  
  <pre><code>ProvincePolled  CandidateA  CandidateB  Ontario CandidateA  Ontario CandidateB  BC CandidateA   BC CandidateB   Quebec CandidateA   Quebec CandidateB
  0   Ontario 33.1    12.1    0.0 0.0 0.0 0.0 0.0 0.0
  1   Ontario 31.3    15.3    0.0 0.0 0.0 0.0 0.0 0.0
  2   BC  27.7    28.7    0.0 0.0 0.0 0.0 0.0 0.0
  3   Quebec  33.3    11.3    0.0 0.0 0.0 0.0 0.0 0.0
  4   Canada  30.0    18.0    0.0 0.0 0.0 0.0 0.0 0.0
  </code></pre>
  
  <p>The following statement doesn't correctly determine the province column:</p>
  
  <pre><code>df.loc[df['ProvincePolled'] != 'Canada', df['ProvincePolled'] + ' CandidateA'] = df.loc[df['ProvincePolled'] != 'Canada', 'CandidateA']
  </code></pre>
  
  <p>as it results in KeyError: "['Canada CandidateA'] not in index".</p>
  
  <p>I also tried defining a function </p>
  
  <pre><code>def fill_cols(row,cols,from_col):
    for col in cols:
      row[col] = from_col
  
  df.loc[df['ProvincePolled'] != 'Canada'] = df.locdf['ProvincePolled'] != 'Canada'].apply(lambda x: fill_cols(x,['Ontario CandidateA','Quebec CandidateA','BC CandidateA'],x['CandidateA'])
  </code></pre>
  
  <p>But this didn't work either, yielding KeyError: ('CandidateA', 'occurred at index ProvincePolled').</p>