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>IIUC, you could group the clusters as follows:</p>

<p>Taking the difference between the row and it's next row , filling the topmost row with 0 and finding it's cumulative sum for both the Labels[1 and 2].</p>

<pre><code>In [2]: label1_ = df['Label1'].diff().fillna(0).cumsum()

In [3]: label2_ = df['Label2'].diff().fillna(0).cumsum()
</code></pre>

<p>Concatenating these to a new dataframe and dropping the duplicated values separately for both Labels[1 and 2]. Followed by <code>reset_index</code> to get back the default integer index.</p>

<pre><code>In [4]: df_ = pd.concat([label1_, label2_], axis=1).drop_duplicates(['Label1'])    \
                                                   .drop_duplicates(['Label2'])     \
                                                   .reset_index()
</code></pre>

<p>Assigning the index values  to a new column, Cluster ID.</p>

<pre><code>In [5]: df_['Cluster_ID'] = df_.index

In [6]: df_.set_index('index', inplace=True)

In [7]: df['Cluster_ID'] = df_['Cluster_ID']
</code></pre>

<p>Replacing <code>Nan</code> values with it's previous finite value and casting the final answer as an integer.</p>

<pre><code>In [8]: df.fillna(method='ffill').astype(int)
Out[8]: 
   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>

python pandas dataframe