我有一个以 CountryName 作为索引并将其 GDP 值作为列的数据框。我正在尝试找到 GDP 最高的国家/地区之前的索引(国家/地区名称)。
CountryName GDP
US 350
UK 370
Australia 340
Germany 500
France 450
如果我这样做,df['GDP'].idxmax()
,它将返回 Germany
。但是有没有简单的方法返回Australia
? (最大索引之前的索引)。
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'