python - 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).
解决方案
在这种情况下,数据框的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'
推荐阅读
- java - 为什么 CompletableFuture 在单独的流中加入/获取比使用一个流更快
- ios - carthage build --no-skip-current --cache-builds --platform iOS 时找不到任何适用于 iOS 的模拟器
- r - 使用 dplyr 的单位不一致
- powerbi - Power BI:计算列当前行的平均值除以第一行
- c++ - 如何使我的类在 Visual Studio 中像 std::array 和 std::vector 一样调试友好?
- google-cloud-platform - 对复杂对象数组的 Google Datastore 投影查询
- arrays - 如何使用 Twig 在 *.html 中打印 *.json 文件的值
- excel - 如何选择宏链接超链接旁边的单元格
- drupal-7 - MAMP 更改文档根目录需要重新导入 sql 数据库
- terraform - Terraform:模块的名称可以动态解析吗?