Home > Net >  Pandas: Get the index of the first value greater than all subsequent values
Pandas: Get the index of the first value greater than all subsequent values

Time:04-19

Let's say I have the following pandas DataFrame:

index A B C
0 2 1 4
1 1 2 3
2 4 3 2
3 3 4 1

I want to get the index of the row in each column where the value of the column at that row is greater than all subsequent rows. So in this example, my desired output would be

A B C
2 3 0

What is the most efficient way to do this?

CodePudding user response:

In that case, I guess I would use:

df.idxmax()

Or to get it formatted to your desired output:

pd.DataFrame(df.idxmax()).T

CodePudding user response:

df[::-1].idxmax(axis=0)

Explanation: indices of last maximum values, by first reversing the row order such that index of first (i.e. lowest) occurrence is used (documentation for DataFrame.idxmax says index of first occurrence of maximum). The following code produces the desired result (as a pd.DataFrame):

df = pd.DataFrame(
    [[2, 1, 4], [1, 2, 3], [4, 3, 2], [3, 4, 1]],
    index=[0, 1, 2, 3], columns=['A', 'B', 'C']
)
pd.DataFrame(df[::-1].idxmax(axis=0)).T

"index of the first value greater than all subsequent rows" <-> "index of last occurrence of maximum value"

  • Related