【问题标题】:How to add offset to TimedeltaIndex in pandas Dataframe如何在 Pandas Dataframe 中为 TimedeltaIndex 添加偏移量
【发布时间】:2021-11-10 15:46:23
【问题描述】:

如何使用 TimedeltaIndex 向 Panda Dataframe 添加偏移量?

dfN.index

输出:

TimedeltaIndex([       '00:00:00', '00:00:00.100000', '00:00:00.200000',
                '00:00:00.300000', '00:00:00.400000', '00:00:00.500000',
                '00:00:00.600000', '00:00:00.700000', '00:00:00.800000',
                '00:00:00.900000',
                ...
                '01:56:26.700000', '01:56:26.800000', '01:56:26.900000',
                       '01:56:27', '01:56:27.100000', '01:56:27.200000',
                '01:56:27.300000', '01:56:27.400000', '01:56:27.500000',
                '01:56:27.600000'],
               dtype='timedelta64[ns]', name='timestamps', length=69877, freq='100L')

这不起作用:

dfN.index += Offset #Offset = 100

输出

TypeError: Addition/subtraction of integers and integer-arrays with TimedeltaArray is no longer supported.  Instead of adding/subtracting `n`, use `n * obj.freq`

在这种情况下,数据每 100 毫秒间隔一次。我想添加和偏移 500 毫秒。

【问题讨论】:

    标签: python pandas datetime offset timedelta


    【解决方案1】:

    变量Offset 不能是整数。您需要创建一个 Timedelta 对象来添加它。试试这个:

    dfN.index += pd.Timedelta(100, unit=‘milliseconds’) #This will add 100 miliseconds
    

    dfN.index += pd.Timedelta(milliseconds = 100)
    

    【讨论】:

    • pd.Timedelta(milliseconds=100)。 +1
    • @Corralien 太棒了,如果我将这个添加到答案中可以吗?
    • @Mark 我很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 2021-07-22
    • 2018-03-24
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2021-06-22
    • 2012-11-15
    相关资源
    最近更新 更多