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

如何为计算DataFrame时间区间均值的函数设置默认参数?

修改函数支持默认参数调用

要让你的custom_mean函数在未传入参数时自动使用合理的默认值计算,只需要给x和y参数设置默认值即可。最合理的默认行为应该是计算整个时间区间内Test 1的均值,所以我们可以把默认值设为Time列的最小值和最大值。

修改后的函数代码

import pandas as pd

# 你的原始DataFrame
df = pd.DataFrame({
    'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88, 2.05, 2.98, 3.45, 3.99, 4.06],
    'Test 1':[5, 9, 4, 6, 4, 1, 6, 8, 2, 9, 3, 9, 4]
})

def custom_mean(x=None, y=None):
    # 当参数未传入时,使用Time列的极值作为默认值
    default_x = df['Time'].min()
    default_y = df['Time'].max()
    
    # 替换未传入的参数
    x = x if x is not None else default_x
    y = y if y is not None else default_y
    
    return df.loc[df['Time'].between(x, y), 'Test 1'].mean()

调用方式示例

  • 无参数调用(计算全区间均值):
    custom_mean()  # 返回整个Time区间内Test 1的均值
    
  • 只传入起始时间x:
    custom_mean(x=1.0)  # 计算Time从1.0到最大值的Test 1均值
    
  • 只传入结束时间y:
    custom_mean(y=2.0)  # 计算Time从最小值到2.0的Test 1均值
    
  • 传入完整区间(和原函数功能一致):
    custom_mean(0.5, 3.0)  # 计算0.5到3.0区间内的均值
    

额外优化建议

如果想让函数更通用、不依赖全局的df变量,可以把DataFrame也作为参数传入,这样同一个函数可以复用在不同的数据集上:

def custom_mean(df, x=None, y=None):
    default_x = df['Time'].min()
    default_y = df['Time'].max()
    x = x if x is not None else default_x
    y = y if y is not None else default_y
    return df.loc[df['Time'].between(x, y), 'Test 1'].mean()

# 调用示例
custom_mean(df)  # 全区间均值
custom_mean(df, 1.5, 3.5)  # 指定区间均值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:54:51