python - 需要显示最高价格和拥有它的公司
问题描述
所以,我刚开始使用 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
并通过以下方式获取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.loc
get 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
推荐阅读
- css - 如何更改奇数列的 p:panelGrid 样式?
- android - 前台服务与 WorkManager
- python - 将抓取的数据写入 CSV 文件中的新列
- mysql - MySQL脚本中显示的方形字符
- php - OneSignal 推送通知发送给所有用户而不是一个玩家
- c++ - ostream 和 ofstream 运算符重载歧义问题
- docker - 如何将 .env 或 docker-compose.yaml 文件中的变量传递给 nginx 服务器文件
- java - 为什么字符串返回为“4-5 u043Bu0435u0442 103-112 u0441u043C”?
- iis - Google API 调用在生产网络服务器上挂起
- php - 使用 json 列连接表