Determine column value based on 2 other columns
<p>There are 2 column, Label1 and Label2. Both of them are cluster labels using different methods. </p>

<pre><code>  Label1 Label2
0   0    1024
1   1    1024
2   2    1025
3   3    1026
4   3    1027
5   4    1028
</code></pre>

<p>I wanna get the final cluster label based these 2 columns. Compared each row, as long as one of these two labels are same, they are in the same cluster.</p>

<p>For example: row 0 and row 1 have label 2 in common, row 3 and row 4 have label1 in common, thus row0 and row1 in the same group and row3 and row4 in the same group.  So the results I'd like to have:</p>

<pre><code>   Label1 Label2 Cluster ID
0   0    1024    0
1   1    1024    0
2   2    1025    1
3   3    1026    2
4   3    1027    2
5   4    1028    3
</code></pre>

<p>What's the best way to do thisï¼
Any help would be appreciated.</p>

<p>Edited: I think I didn't give a good example. Acutally,  labels are not necessarily in any order:</p>

<pre><code>  Label1 Label2
0   0    1024
1   1    1023
2   2    1025
3   3    1024
4   3    1027
5   4    1022
</code></pre>

<p>Here is how you can implement this:</p>

<ol>
<li><p>Check previous row for same value for the two columns</p></li>
<li><p>If either of the values is same, do not increment cluster number and add to cluster list</p></li>
<li><p>If none of the values is same, increment cluster number and add to cluster list</p></li>
<li><p>Add cluster list as column to the dataframe.</p></li>
</ol>

<p>Code:</p>

<pre><code>import pandas as pd

df=pd.DataFrame([[0,1,2,3,4,5],[0,1,2,3,3,4],[1024,1024,1025,1026,1027,1028]]).T
cluster_num = 0
cluster_list = []
for i,row in df.iterrows():
    if i!=0:
        # check previous row
        if df.loc[i-1][1]==row[1] or df.loc[i-1][2]==row[2]:
            # add to previous cluster
            cluster_list.append(cluster_num)
        else:
            # create new cluster
            cluster_num+=1
            cluster_list.append(cluster_num)
    else:
        cluster_list.append(cluster_num)

#Add the list as column
df.insert(3,3,cluster_list)
</code></pre>

python pandas dataframe