df.max()未返回数据集中的最高值

2024-05-16 17:50:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是完整的Python新手。我有一个小数据集,我想返回一行,其中该行中的一列使用pandas和df.max()是最高的

这是我的数据集:

Destination,     Score,Star Rating,Bags,City
---------------------------------------------------
Australia,       8,    4,          1,   Sydney
Papua New Guinea,7,    4,          2,   Port Moresby
Fiji,            9,    3,          2,   Suva
New Zealand,     8,    4,          1,   Wellington
Western Samoa,   6,    5,          2,   Apia
Tuvalu,          5,    4,          1,   Funafuti
French Polynesia,8,    3,          1,   Pape'ete
Tonga,           6,    2,          2,   Nuku'alofa
Christmas Island,7,    3,          2,   Flying Fish Cove
Cook Islands,    8,    4,          1,   Avarua District
Solomon Islands, 5,    3,          2,   Honiara

我使用以下命令返回Score列中最高值的行。这应该是Fiji,分数为9

这是我的密码:

import pandas as pd

frame = pd.read_csv("Australasia.csv")
df = pd.DataFrame(frame)
print("The highest scoring destination is: "+ str(df.loc[df["Score"].max()]))

出于某种原因,这会不断返回得分为Cook Islands8

The highest scoring destination is: 
Destination       Cook Islands
Score                        8
Star Rating                  4
Bags                         1
City           Avarua District
Name: 9, dtype: object

有没有人能提供一些建议,说明为什么这不会返回分数列中的最高值,即9而不是8

我对df.min()使用了与此完全相反的方法,没有问题,也不知道max为什么不工作


Tags: 数据citypandasdfnewdestinationbagsmax
1条回答
网友
1楼 · 发布于 2024-05-16 17:50:16

这将有助于:

import pandas as pd

frame = pd.read_csv('Australia.csv')
max_score = frame['Score'].max()
print(f'Max score is {max_score}')
best_destinations = ','.join(frame[frame['Score'] == max_score]['Destination'].to_list())
print(f'Area(s) with max_score : {best_destinations}')

输出:

Max score is 9
Area(s) with max_score : Fiji

相关问题 更多 >