numpy 沿轴应用不适用于工作日

numpy apply along axis not working with weekday

我有一个 numpy 数组:

>>> type(dat)
Out[41]: numpy.ndarray

>>> dat.shape
Out[46]: (127L,)

>>> dat[0:3]
Out[42]: array([datetime.date(2010, 6, 11), datetime.date(2010, 6, 19), datetime.date(2010, 6, 30)], dtype=object)

我想获取此数组中每个日期的工作日,如下所示:

>>> dat[0].weekday()
Out[43]: 4

我尝试使用以下但 none 工作:

import pandas as pd
import numpy as np
import datetime as dt

np.apply_along_axis(weekday,0,dat)
NameError: name 'weekday' is not defined

np.apply_along_axis(dt.weekday,0,dat)
AttributeError: 'module' object has no attribute 'weekday'

np.apply_along_axis(pd.weekday,1,dat)
AttributeError: 'module' object has no attribute 'weekday'

np.apply_along_axis(lambda x: x.weekday(),0,dat)
AttributeError: 'numpy.ndarray' object has no attribute 'weekday'

np.apply_along_axis(lambda x: x.dt.weekday,0,dat)
AttributeError: 'numpy.ndarray' object has no attribute 'dt'

我在这里遗漏了什么吗?

您可以尝试将工作日函数矢量化,以便您可以按元素将其应用于数组。

weekday_func = lambda x: x.weekday()
get_weekday = np.vectorize(weekday_func)
get_weekday(dat)

np.apply_along_axis 对于一维数组没有多大意义。在 2d 或更高的数组中,它将函数应用于该数组中的 1d 切片。关于那个函数:

This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

这个nameerror甚至在运行apply之前就产生了。您没有定义 weekday 函数:

np.apply_along_axis(weekday,0,dat)
NameError: name 'weekday' is not defined

weekday是日期的方法,不是dt模块中的函数:

np.apply_along_axis(dt.weekday,0,dat)
AttributeError: 'module' object has no attribute 'weekday'

它也没有在 pandas 中定义:

np.apply_along_axis(pd.weekday,1,dat)
AttributeError: 'module' object has no attribute 'weekday'

这看起来更好,但是 apply_along_axis 将数组 (1d) 传递给 lambdaweekday 不是数组方法。

np.apply_along_axis(lambda x: x.weekday(),0,dat)
AttributeError: 'numpy.ndarray' object has no attribute 'weekday'

数组也没有 dt 属性。

np.apply_along_axis(lambda x: x.dt.weekday,0,dat)
AttributeError: 'numpy.ndarray' object has no attribute 'dt'

所以让我们忘记 apply_along_axis


定义一个样本,首先是列表,然后是对象数组:

In [231]: alist = [datetime.date(2010, 6, 11), datetime.date(2010, 6, 19), datetime.date(2010, 6, 30)]
In [232]: data = np.array(alist)
In [233]: data
Out[233]: 
array([datetime.date(2010, 6, 11), datetime.date(2010, 6, 19),
       datetime.date(2010, 6, 30)], dtype=object)

为了方便起见,weekday 的 lambda 版本:

In [234]: L = lambda x: x.weekday()

这可以通过多种方式迭代应用:

In [235]: [L(x) for x in alist]
Out[235]: [4, 5, 2]
In [236]: [L(x) for x in data]
Out[236]: [4, 5, 2]
In [237]: np.vectorize(L)(data)
Out[237]: array([4, 5, 2])
In [238]: np.frompyfunc(L,1,1)(data)
Out[238]: array([4, 5, 2], dtype=object)

我刚刚对 3000 项列表进行了时间测试。列表理解是最快的(正如我从过去的测试中预期的那样),但时间差异并不大。最大的一次消耗只是运行x.weekday()3000次