title: enumerate equal elements within dataframe column
body: <p>I would like to enumerate elements in a column which appear more than once. Elements that appear only once should not be modified.</p>
  
  <p>I have come up with two solutions, but they seem to be very inelegant, and I am hoping that there is a better solution.</p>
  
  <pre><code>Input:
     X
  0  A
  1  B
  2  C
  3  A
  4  C
  5  C
  6  D
  
  Output:
    new_name
  X         
  A       A1
  A       A2
  B        B
  C       C1
  C       C2
  C       C3
  D        D
  </code></pre>
  
  <p>Here are two possible ways of achieving this, one using <code>.expanding().count()</code>, the other using <code>.cumcount()</code>, but both pretty ugly</p>
  
  <pre><code>import pandas as pd
  
  def solution_1(df):
      pvt = (df.groupby(by='X')
                 .expanding()
                 .count()
                 .rename(columns={'X': 'Counter'})
                 .reset_index()
                 .drop('level_1', axis=1)
                 .assign(name = lambda s: s['X'] + s['Counter'].astype(int).astype(str))
                 .set_index('X')
                 )
  
      pvt2 = (df.reset_index()
              .groupby(by='X')
              .count()
              .rename(columns={'index': 'C'}
              ))
  
      df2 = pd.merge(left=pvt, right=pvt2, left_index=True, right_index=True)
  
      ind=df2['C']&gt;1
      df2.loc[ind, 'new_name']=df2.loc[ind, 'name']
      df2.loc[~ind, 'new_name']=df2.loc[~ind].index
      df2 = df2.drop(['Counter', 'C', 'name'], axis=1)
  
      return df2
  
  def solution_2(df):
  
      pvt = pd.DataFrame(df.groupby(by='X')
                          .agg({'X': 'cumcount'})
              ).rename(columns={'X': 'Counter'})
  
      pvt2 = pd.DataFrame(df.groupby(by='X')
                          .agg({'X': 'count'})
              ).rename(columns={'X': 'Total Count'})
      # print(pvt2)
  
      df2 = df.merge(pvt, left_index=True, right_index=True)
      df3 = df2.merge(pvt2, left_on='X', right_index=True)
  
      ind=df3['Total Count']&gt;1
      df3['Counter'] = df3['Counter']+1
      df3.loc[ind, 'new_name']=df3.loc[ind, 'X']+df3.loc[ind, 'Counter'].astype(int).astype(str)
      df3.loc[~ind, 'new_name']=df3.loc[~ind, 'X']
      df3 = df3.drop(['Counter', 'Total Count'], axis=1).set_index('X')
      return df3
  
  if __name__ == '__main__':
  
      s = ['A', 'B', 'C', 'A', 'C', 'C', 'D']
      df = pd.DataFrame(s, columns=['X'])
      print(df)
      sol_1 = solution_1(df)
      print(sol_1)
      sol_2 = solution_2(df)
      print(sol_2)
  
  </code></pre>
  
  <p>Any suggestions? Thanks a lot.</p>