python - Pandas DatetimeIndex.weekday 应该返回索引还是 numpy 数组?

标签 python pandas datetimeindex

我有一个 Pandas DatetimeIndex 对象(从数据帧的索引获得),我需要每个元素的工作日。我一直在 Windows 上使用 Python 3.6.5(64 位)和 Pandas 0.22.0 运行此程序并获取 Int64Index 对象:

例如

In:
    ts = pd.DatetimeIndex([['2013-01-01 00:00:00', '2013-01-01 00:30:00',
               '2013-01-02 01:00:00', '2013-01-02 01:30:00',
               '2013-01-03 02:00:00', '2013-01-03 02:30:00',
               '2013-01-04 03:00:00', '2013-01-04 03:30:00',
               '2013-01-05 04:00:00', '2013-01-05 04:30:00']])
    ts.weekday

Out:
    Int64Index([1, 1, 2, 2, 3, 3, 4, 4, 5, 5], dtype='int64')

我现在正在 pythonanywhere 上运行脚本,该脚本具有 Python 3.6.0Pandas 0.19.2 ,结果作为数组:

In:        
    ts = pd.DatetimeIndex(['2013-01-01 00:00:00', '2013-01-01 00:30:00',
                    '2013-01-02 01:00:00', '2013-01-02 01:30:00',
                    '2013-01-03 02:00:00', '2013-01-03 02:30:00',
                    '2013-01-04 03:00:00', '2013-01-04 03:30:00',
                    '2013-01-05 04:00:00', '2013-01-05 04:30:00'])
        ts.weekday
    Out:
        array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5], dtype=int32)

是否可以编写此代码以在两个平台上返回相同的结果(最好是 Index 对象)?

最佳答案

此行为在最近的更新中已更改,以返回 pd.Index 而不是数组。为了向后兼容,您始终可以根据需要将结果转换为 Int64Index

>>> pd.Index(ts.weekday, dtype=np.int64)
Int64Index([1, 1, 2, 2, 3, 3, 4, 4, 5, 5], dtype='int64')

关于python - Pandas DatetimeIndex.weekday 应该返回索引还是 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902204/

相关文章:

python - 使用 Pandas AWS Glue Python Shell 作业

python - 内存错误:- How to get data from one dataframe to another using one common ID column?

python - Xpath从具有样式属性的父标签解析子标签时出现问题

python - 如何在 pyqt 中同时运行 2 个线程?

python - Pandas - 填充时间序列数据中缺失的时间

python - 将新的日期时间添加到具有值的日期时间索引 Pandas 数据框

python - pandas - 使用 DateTimeIndex 切片 DataFrame 的 Pythonic 方法

python - 在 Django Admin 中将 ManyToManyWidget 添加到 ManyToManyField 的反面

带有打印函数结果的 Python sys.argv TypeErrors?

pandas - 如何在 Pandas Dataframe 中扩展 date_range?