title: Renaming pandas data frame columns using a for loop
body: <p>I'm not sure if this is a dumb way to go about things, but I've got several data frames, all of which have identical columns. I need to rename the columns within each to reflect the names of each data frame (I'll be performing an outer merge of all of these afterwards). </p>
  
  <p>Let's say the data frames are called <code>df1</code>, <code>df2</code> and <code>df3</code>, and each contains the columns <code>name</code>, <code>date</code>, and <code>count</code>. </p>
  
  <p>I'd like to rename each of the columns in <code>df1</code> into <code>name_df1</code>, <code>date_df1</code>, and <code>count_df1</code>. </p>
  
  <p>I've written a function to rename the columns, thus: </p>
  
  <pre><code>df_list=[df1, df2, df3]
  
  def rename_cols():
      col_name="name"+suffix
      col_count="count"+suffix
      col_date="date"+suffix
  
  for x in df_list:
      if x['name'].tail(1).item() == df1['name'].tail(1).item():
          suffix="_"+"df1"
          rename_cols()
          continue
      elif x['name'].tail(1).item() == df2['name'].tail(1).item():
          suffix="_"+"df2"
          rename_cols()
          continue
      else:
          suffix="_"+"df3"
          rename_cols()
  
      col_names=[col_name,col_date,col_count]
      x.columns=col_names
  </code></pre>
  
  <p>Unfortunately, I get the following error: <code>KeyError: 'name'</code></p>
  
  <p>I'm really struggling to figure out why that's going on. The columns for df1, the first data frame in the <code>df_list</code>, gets renamed. Everything else stays the same... Am I messing up basic syntax (probably), or is there a fundamental misunderstanding that I've got of how things should work? </p>
  
  <p>From what I can ascertain, the first data frame in the list is being iterated through more than once — but why would that be the case?</p>