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

如何在Pandas中直接将DateTimeIndex传入自定义函数使用apply()?

如何直接对DateTimeIndex使用apply调用自定义函数?

你碰到的问题核心在于:DatetimeIndex本身没有apply方法,而df15.index.weekday返回的是numpy数组,同样不支持apply。下面给你几个直接解决的方案,不用创建中间列:

方案1:把DateTimeIndex转为Series后调用apply

直接用pd.Series()把你的索引包装成Series,这样就能使用apply方法调用你写的weekend函数了:

df15['Type of day'] = pd.Series(df15.index).apply(weekend)

这个方法完全复用你现有的第一个函数,不需要做任何修改。

方案2:用numpy向量化函数处理

如果你想继续用针对weekday数值的weekendfromnumber函数,可以用np.vectorize()把它转换成能直接作用于numpy数组的向量化函数:

import numpy as np
vectorized_weekend = np.vectorize(weekendfromnumber)
df15['Type of day'] = vectorized_weekend(df15.index.weekday)

这样就不用先创建中间列,直接对index.weekday的结果处理。

方案3:用pandas/numpy内置方法(推荐,更高效)

其实对于这种简单的判断,完全不需要自定义函数,用np.where可以直接实现,而且速度比apply快得多(尤其是数据量大的时候):

import numpy as np
df15['Type of day'] = np.where(df15.index.weekday >= 5, "Weekend", "Working day")

这个写法更简洁,也避免了逐元素遍历的性能损耗。

为什么之前的尝试会报错?

  • 第一个错误:AttributeError: 'DatetimeIndex' object has no attribute 'apply'
    DatetimeIndex是pandas的索引类,它没有提供apply方法——apply是Series和DataFrame特有的方法,所以直接调用索引的apply会失败。
  • 第二个错误:AttributeError: 'numpy.ndarray' object has no attribute 'apply'
    df15.index.weekday返回的是一个numpy数组,numpy数组也没有apply方法,只有pandas的Series才有,所以这也会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:33:37