熊猫时间戳不规则地舍入30秒

Pet*_*ter 4 python pandas datetimeindex

我正在尝试将熊猫的DatetimeIndex(或Timestamp)四舍五入到最近的分钟,但是Timestamps为30秒时出现了问题-有些向上舍入,有些向下舍入(这似乎是交替的)。

有什么建议可以解决此问题,以使30s总是四舍五入吗?

>>> pd.Timestamp(2019,6,1,6,57,30).round('1T')
Timestamp('2019-06-01 06:58:00')

>>> pd.Timestamp(2019,6,1,6,58,30).round('1T')
Timestamp('2019-06-01 06:58:00')
Run Code Online (Sandbox Code Playgroud)

最高结果看起来不错,其中57m 30s会四舍五入为58m,但是我希望最低结果会舍入到59m-不减少到58m。

WeN*_*Ben 6

这是ceil圆的

pd.Timestamp(2019,6,1,6,57,30).ceil('1T')
Out[344]: Timestamp('2019-06-01 06:58:00')
pd.Timestamp(2019,6,1,6,58,30).ceil('1T')
Out[345]: Timestamp('2019-06-01 06:59:00')
Run Code Online (Sandbox Code Playgroud)

更新,这是十进制问题

from decimal import Decimal, ROUND_HALF_UP
s=Decimal((pd.Timestamp(2019,6,1,6,58,30).value//60)/1e9).quantize(0, ROUND_HALF_UP)
pd.to_datetime(int(s)*60*1e9)
Out[28]: Timestamp('2019-06-01 06:59:00')
s=Decimal((pd.Timestamp(2019,6,1,6,57,30).value//60)/1e9).quantize(0, ROUND_HALF_UP)
pd.to_datetime(int(s)*60*1e9)
Out[30]: Timestamp('2019-06-01 06:58:00')
Run Code Online (Sandbox Code Playgroud)


ALo*_*llz 3

舍入一致;接下来的选择是,“当两个整数之间的中间时,选择偶数”。您需要半向上舍入,这需要您自己实现。

import numpy as np
import pandas as pd

def half_up_minute(x):
    m = (x - x.dt.floor('1T')).dt.total_seconds() < 30   # Round True Down, False Up
    return x.where(m).dt.floor('1T').fillna(x.dt.ceil('1T'))

# For indices:
def half_up_minute_idx(idx):
    m = (idx - idx.floor('1T')).total_seconds() < 30   # Round True Down, False Up
    return pd.Index(np.select([m], [idx.floor('1T')], default=idx.ceil('1T')))

# Sample Data
df = pd.DataFrame({'date': pd.date_range('2019-01-01', freq='15S', periods=10)})
df['rounded'] = half_up_minute(df.date)
Run Code Online (Sandbox Code Playgroud)

输出:

                 date             rounded
0 2019-01-01 00:00:00 2019-01-01 00:00:00
1 2019-01-01 00:00:15 2019-01-01 00:00:00
2 2019-01-01 00:00:30 2019-01-01 00:01:00
3 2019-01-01 00:00:45 2019-01-01 00:01:00
4 2019-01-01 00:01:00 2019-01-01 00:01:00
5 2019-01-01 00:01:15 2019-01-01 00:01:00
6 2019-01-01 00:01:30 2019-01-01 00:02:00
7 2019-01-01 00:01:45 2019-01-01 00:02:00
8 2019-01-01 00:02:00 2019-01-01 00:02:00
9 2019-01-01 00:02:15 2019-01-01 00:02:00
Run Code Online (Sandbox Code Playgroud)