You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:对Movehub生活质量CSV多列排序并获取前5条记录

Fixing Your Pandas Sorting Code for Kaggle Dataset

Hey there! Let's get your code working to pull the top 5 records you need. Here's what was off with your original approach, plus the corrected version:

Issues in Your Original Code

  • You didn't save the sorted results: The sort_values() method returns a new sorted DataFrame by default—it doesn't change the original one unless you explicitly tell it to. Your code was sorting but not retaining those sorted rows.
  • Redundant CSV reads: You loaded the same file twice, which isn't necessary. We can handle everything with a single DataFrame.
  • Missing multi-column sorting: You need to sort by both Movehub Rating (descending) and Health Care (ascending) to get the exact order you want.

Corrected Code

import pandas as pd

# Load the dataset once
df = pd.read_csv("movehubqualityoflife.csv")

# Sort by Movehub Rating (highest first), then Health Care (lowest first for ties)
df_sorted = df.sort_values(
    by=['Movehub Rating', 'Health Care'],
    ascending=[False, True]
)

# Grab the top 5 records
top_5_records = df_sorted.head(5)

# Output the results
print(top_5_records)

Key Details Explained

  • by=['Movehub Rating', 'Health Care']: Pandas will first sort all rows by Movehub Rating in descending order. For any rows with identical ratings, it will then sort those by Health Care in ascending order (so the worst health care scores come first among tied ratings).
  • ascending=[False, True]: This pair of values aligns with our sorting priorities—False for descending (highest rating first), True for ascending (lowest health care first).
  • head(5): After sorting, this pulls the first 5 rows, which are exactly the records you need.

内容的提问来源于stack exchange,提问作者Brandon McMullen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:39