如何用Pandas将排序后的DataFrame存储到新变量,筛选极值树木数据?
解决方案
要保留原始DataFrame不变,只需去掉sort_values方法的inplace=True参数,将排序后的结果赋值给新变量即可。这样原始数据不会被修改,新变量中存储的是排序后的数据集,直接取首行就能得到目标结果。
修改后的代码如下:
import pandas as pd # 读取原始数据,原DataFrame保持不变 trees = pd.read_csv('redwood_data.txt', delimiter='\t') # 按直径降序排序,结果存入新变量 sorted_by_diameter = trees.sort_values('diameter (m)', ascending=False) max_diam_tree = sorted_by_diameter.iloc[0] print(f"The tree with the largest diameter is {max_diam_tree['Tree name']} with a diameter of {max_diam_tree['diameter (m)']} m.") # 按高度降序排序,结果存入新变量 sorted_by_height = trees.sort_values('height (m)', ascending=False) max_height_tree = sorted_by_height.iloc[0] print(f"The tree with the highest height is {max_height_tree['Tree name']} with a height of {max_height_tree['height (m)']} m.")
关键说明:
sort_values默认返回排序后的新DataFrame,赋值给新变量后,原始的trees数据不会被修改- 使用
iloc[0]获取排序后的第一行,比直接用[0]更可靠,避免原索引混乱导致的取值错误 - 用f-string格式化输出代码更简洁易读
内容的提问来源于stack exchange,提问作者user16342430
相关产品推荐
相关产品推荐

