首页 > 解决方案 > How to find index before the max-value index, idxmax()?

问题描述

I have a dataframe with CountryName as the index and values for their GDP as a column. I'm trying to find the index (the country name) that comes before the country with the max GDP.

CountryName   GDP 
US             350
UK             370 
Australia      340 
Germany        500 
France         450

If i do, df['GDP'].idxmax() , it'll return Germany. But is there a simple way to return Australia? (the index before the max index).

标签: pythonpandas

解决方案


在这种情况下,数据框的shift方法可以帮助您。

# Initialize dataframe
import pandas as pd
df = pd.DataFrame({
    'CountryName': ['US', 'UK', 'Australia', 'Germany', 'France'],
    'GDP': [350, 370, 340, 500, 450],
})
df = df.set_index('CountryName')

# Get the index value of the row directly before the row with max 'GDP' value
target = df['GDP'].shift(-1).idxmax()

结果:

In [1]: target
Out[1]: 'Australia'

推荐阅读