Question: i have a dataframe as below.

```
test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]})
   col1  col2
0     0     0
1     0     0
2     1     1
3     0     2
4     0     3
5     0     0
6     1     0
7     2     0
8     0     0

```

For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. 

In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?

Answer: 
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column.

```
m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) 
test.mask(m).apply(pd.Series.last_valid_index)

col1    6
col2    2
dtype: int64

```

---

Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html):

```
idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0))
            .values
            .cumsum(axis=0)
            .argmax(axis=0))
idx
# array([6, 2])

pd.Series(idx, index=[*test])

col1    6
col2    2
dtype: int64

```
Using @cs95 idea of `last_valid_index`:

```
test.apply(lambda x: x[:x.idxmax()].eq(1)[lambda i:i].last_valid_index())

```

Output:

```
col1    6
col2    2
dtype: int64

```

Expained:

Using index slicing to cut each column to start to max value, then look for the values that are equal to one and find the index of the last true value.

Or as @QuangHoang suggests:

```
test.apply(lambda x: x[:x.idxmax()].eq(1).cumsum().idxmax()) 

```