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