首页 > 解决方案 > 使用 Pandas 查找特定列的“最大值”,然后输出该 VALUE 以及同一行中的相应 ITEM

问题描述

我了解如何找到“CONTRCOST”列的最大值,但是如何获取相应的值并将两条信息输入到字符串中,就像它要求我做的那样?

标签: pythonarrayspandasnumpylambda

解决方案


我相信这应该给你你想要的。该idxmax()函数返回具有最大值的行的索引。如果有多个,则返回第一个。

import pandas as pd

data = [{'id':0,'city':'Chicago','contrcost':1000000.00},
{'id':1,'city':'New York','contrcost':2000000.00},
{'id':2,'city':'Boston','contrcost':1000000.00},
{'id':3,'city':'Atlanta','contrcost':1000000.00},
{'id':4,'city':'Los Angeles','contrcost':2000000.00}]

df = pd.DataFrame(data)
max_index = df['contrcost'].idxmax()
print('City with the contract that has the greatest cost: {:s} (contract cost is ${:.2f})'
.format( df.iloc[max_index]['city'], df.iloc[max_index]['contrcost']))

输出:合同成本最高的城市:纽约(合同成本为 2000000.00 美元)


推荐阅读