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

```
Here's a mixed `numpy` and `pandas` solution:

```
(test.eq(1) & (test.index.values[:,None] < test.idxmax().values)).cumsum().idxmax()

```

which is a bit faster than the other solutions.