首页 > 解决方案 > 需要显示最高价格和拥有它的公司

问题描述

所以,我刚开始使用 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)

标签: pythonpandas

解决方案


使用Series.max、创建索引DataFrame.set_index并通过以下方式获取company名称Series.idxmax

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.locget Series

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

推荐阅读