consider a data frame of binary numbers:
import pandas
import numpy
numpy.random.seed(123)
this_df = pandas.DataFrame((numpy.random.random(100) < 1/3).astype(int).reshape(10, 10))
0 1 2 3 4 5 6 7 8 9
0 0 1 1 0 0 0 0 0 0 0
1 0 0 0 1 0 0 1 1 0 0
2 0 0 0 0 0 1 0 1 1 0
3 1 0 0 0 0 1 0 0 0 0
4 0 1 1 0 0 1 0 0 0 0
5 1 0 0 0 0 1 0 0 0 0
6 0 0 0 0 0 1 0 1 1 0
7 1 0 0 0 1 0 0 1 1 0
8 1 0 0 0 0 0 0 1 1 0
9 0 0 0 0 0 0 1 0 1 0
how do I find, for each row, the rightmost column in which a 1 is observed?
so for the dataframe above it would be:
[2, 7, 8,....,8]
CodePudding user response:
One option is to reverse the column order, then use idxmax
:
df['rightmost 1'] = df.loc[:,::-1].idxmax(axis=1)
Output:
0 1 2 3 4 5 6 7 8 9 rightmost 1
0 0 1 1 0 0 0 0 0 0 0 2
1 0 0 0 1 0 0 1 1 0 0 7
2 0 0 0 0 0 1 0 1 1 0 8
3 1 0 0 0 0 1 0 0 0 0 5
4 0 1 1 0 0 1 0 0 0 0 5
5 1 0 0 0 0 1 0 0 0 0 5
6 0 0 0 0 0 1 0 1 1 0 8
7 1 0 0 0 1 0 0 1 1 0 8
8 1 0 0 0 0 0 0 1 1 0 8
9 0 0 0 0 0 0 1 0 1 0 8