Skip to main content
 首页 » 编程设计

python之需要显示最高价格和拥有它的公司

2025年05月04日13bonelee

所以,我刚开始使用 python,我需要显示最高价格和拥有它的公司。我从一个 CSV 文件中获取数据,该文件包含描述某些汽车的多列。我只对其中两个感兴趣:价格和公司。

我需要显示最高价格和拥有它的公司。一些忠告? 这是我尝试过的方法,我也不知道如何获得公司,不仅是最高价格。

import pandas as pd 
df = pd.read_csv("Automobile_data.csv") 
for x in df['price']: 
    if x == df['price'].max(): 
       print(x) 

请您参考如下方法:

使用Series.max , 通过 DataFrame.set_index 创建索引并通过 Series.idxmax 获取 company 名称:

df = pd.DataFrame({ 
        'company':list('abcdef'), 
         'price':[7,8,9,4,2,3], 
 
}) 
 
print (df) 
  company  price 
0       a      7 
1       b      8 
2       c      9 
3       d      4 
4       e      2 
5       f      3 
 
print(df['price'].max()) 
9 
print(df.set_index('company')['price'].idxmax()) 
c 

另一个想法是使用 DataFrame.agg :

s = df.set_index('company')['price'].agg(['max','idxmax']) 
print (s['max']) 
9 
print (s['idxmax']) 
c 

如果可能重复最大值并需要所有公司使用最高价格boolean indexing与 DataFrame.loc - 获取系列:

df = pd.DataFrame({ 
        'company':list('abcdef'), 
         'price':[7,8,9,4,2,9], 
 
}) 
 
print (df) 
  company  price 
0       a      7 
1       b      8 
2       c      9 
3       d      4 
4       e      2 
5       f      9 
 
print(df['price'].max()) 
9 
 
#only first value 
print(df.set_index('company')['price'].idxmax()) 
c 
 
#all maximum values 
s = df.loc[df['price'] == df['price'].max(), 'company'] 
print (s) 
2    c 
5    f 
Name: company, dtype: object 

如果需要一行DataFrame:

out = df.loc[df['price'] == df['price'].max(), ['company','price']] 
print (out) 
  company  price 
2       c      9 
 
 
out = df.loc[df['price'] == df['price'].max(), ['company','price']] 
print (out) 
  company  price 
2       c      9 
5       f      9