Assign Unique Values according Distinct Columns Values
<p>I know the question name is a little ambiguous.</p>

<p>My goal is to assign global key column based on 2 columns + unique value in my data frame.</p>

<p>For example</p>

<pre><code>CountryCode | Accident
   AFG          Car
   AFG          Bike
   AFG          Car
   AFG          Plane
   USA          Car
   USA          Bike
   UK           Car
</code></pre>

<p>Let Car = 01, Bike = 02, Plane = 03</p>

<p>My desire global key format is [Accident][CountryCode][UniqueValue]</p>

<p>Unique value is a count of similar [Accident][CountryCode]</p>

<p>so if Accident = Car and CountryCode = AFG and it is the first occurrence, the global key would be 01AFG01</p>

<p>The desired dataframe would look like this:</p>

<pre><code>CountryCode | Accident | GlobalKey
   AFG          Car        01AFG01
   AFG          Bike       02AFG01
   AFG          Car        01AFG02
   AFG          Plane      01AFG03
   USA          Car        01USA01
   USA          Bike       01USA02
   UK           Car        01UK01
</code></pre>

<p>I have tried running a for loop to append Accident Number and CountryCode together</p>

<p>for example:</p>

<pre><code>globalKey = []

for x in range(0,6):
    string = df.iloc[x, 1]
    string2 = df.iloc[x, 2]
    if string2 == 'Car':
        number = '01'
    elif string2 == 'Bike':
        number = '02'
    elif string2 == 'Plane':
        number = '03'
    #Concat the number of accident and Country Code
    subKey = number + string
    #Append to the list
    globalKey.append(subKey)
</code></pre>

<p>This code will provide me with something like <code>01AFG</code>, <code>02AFG</code> based on the value I assign. but I want to assign a unique value by counting the occurrence of when <code>CountryCode</code> and <code>Accident</code> is similar.</p>

<p>I am stuck with the code above. I think there should be a better way to do it using map function in Pandas.</p>

<p>Thanks for helping guys!
much appreciate!</p>

<p>After you create your <code>subKey</code> we can sort the dataframe and count the occurences of the couples. First let's reset the index (to store the original order)</p>

<pre><code>df = df.reset_index()
</code></pre>

<p>then sort by the <code>subKey</code> and count</p>

<pre><code>df = df.sort_values(by='subKey')
df['newnumber'] = 1

for ind in range(1, len(df)): #start by 1 because first row is always 1
    if df.loc[ind, 'subKey'] == df.loc[ind - 1, 'subKey']:
        df.loc[ind, 'newnumber'] = df.loc[ind - 1, 'newnumber'] + 1
</code></pre>

<p>Finally create the <code>GlobalKey</code> with the help of the <code>zfill</code> function, the reorder by <code>index</code>:</p>

<pre><code>df['GlobalKey'] = df.apply(lambda x: x['subKey'] + str(x['new_number']).zfill(2), 1)
df = df.sort_values(by='index').drop('index', 1).reset_index(drop=True)
</code></pre>

python pandas dataframe group-by