Replacing values in a Pandas data frame with the order of their columns

Viewed 58

How can we replace specific values in a data frame such that the replacements are equal to the order of the ith column where those specific values reside? For example I have this DF:

A  B  C
0  0  1
1  0  0 
1  0  0
0  1  0
1  0  1

Replacing all ones in this data frame with the order of the ith column (1st, 2nd, 3rd, etc) where the 1's reside, so that it loos like this:

A  B  C
0  0  3
1  0  0 
1  0  0
0  2  0
1  0  3

That is what I thought would work, but it did not:

 DF_2= [(0 if i== 0 else j  for i in DF.iloc[:,j]  ) for j in range(DF.shape[1]) ]
2 Answers
Related