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

如何使用pandas将旧dataframe中最大的前5条数据复制到新dataframe

操作方法

你可以直接在排序后链式调用head(5)方法提取前5条数据,搭配字段筛选的完整写法如下:

# 一步完成排序、筛选字段、提取前5条存入新DataFrame
new_dataframe = sort_drop2.sort_values(by='Nti', ascending=False).filter(['City','Est','Nti']).head(5)

如果你已经单独完成了sort_drop2的排序操作,也可以单独提取:

# 假设你已将排序后的结果赋值给了sorted_df
sorted_df = sort_drop2.sort_values(by='Nti', ascending=False)
# 筛选指定字段后取前5行
new_dataframe = sorted_df.filter(['City','Est','Nti']).head(5)

补充说明

如果需要重置新DataFrame的索引,避免保留原数据集的旧索引值,可以在末尾添加reset_index(drop=True):

new_dataframe = sort_drop2.sort_values(by='Nti', ascending=False).filter(['City','Est','Nti']).head(5).reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:36:03