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

基于参考DataFrame列最小值的Pandas数据截断实现

使用Python Pandas实现指定数据处理操作

步骤1:创建原始DataFrame并计算列最小值

导入pandas库,构建题目中的原始DataFrame,并提取各列最小值:

import pandas as pd

# 构建原始df
df = pd.DataFrame({
    'age': [10, 8, 20, 15],
    'money': [300, 200, 1800, 200],
    'time': [10, 20, 80, 50]
})

# 获取每一列的最小值
col_mins = df.min()

步骤2:构建新DataFrame并完成替换操作

构建目标新DataFrame后,使用clip()方法快速完成小于最小值的替换:

# 构建new_df
new_df = pd.DataFrame({
    'age': [30, 10, -2, 18],
    'money': [-100, 100, 1800, -50],
    'time': [15, 50, -20, 52]
})

# 将列中小于对应最小值的元素替换为最小值
result_df = new_df.clip(lower=col_mins, axis=1)

最终结果

执行代码后,result_df的输出与题目要求一致:

agemoneytime
3020015
1020050
8180010
1820052

说明

  • df.min()返回一个Series,存储每一列的最小值,索引与列名一一对应
  • clip(lower=col_mins, axis=1)指定按列匹配下限值,自动完成元素替换,无需逐列遍历判断,简洁高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:42:03