簡體   English   中英

在 pandas 中向上取整半小時

[英]Round up half of the hour in pandas

pandas 中的round() function 將時間從 07:30 向下舍入到 07:00 但我想在超過 30 分鍾(含)的任何時間進行舍入。

例如。

07:15 to 07:00
05:25 to 05:00
22:30 to 23:00
18:45 to 19:00

如何使用 pandas 為 dataframe 的列實現此目的?

時間戳

您需要使用dt.round 然而,這有點因為前一小時/下一小時的行為取決於小時本身。 您可以通過增加或減少少量時間(此處為 1ns)來強制執行它:

s = pd.to_datetime(pd.Series(['1/2/2021 3:45', '25/4/2021 12:30', 
                              '25/4/2021 13:30', '12/4/2022 23:45']))

# xx:30 -> rounding depending on the hour parity (default)
s.dt.round(freq='1h')

0   2021-01-02 04:00:00
1   2021-04-25 12:00:00    <- -30min
2   2021-04-25 14:00:00    <- +30min
3   2022-12-05 00:00:00
dtype: datetime64[ns]


# 00:30 -> 00:00 (force down)
s.sub(pd.Timedelta('1ns')).dt.round(freq='1h')

0   2021-01-02 04:00:00
1   2021-04-25 12:00:00
2   2021-04-25 13:00:00
3   2022-12-05 00:00:00
dtype: datetime64[ns]


# 00:30 -> 01:00 (force up)
s.add(pd.Timedelta('1ns')).dt.round(freq='1h')

0   2021-01-02 04:00:00
1   2021-04-25 12:00:00
2   2021-04-25 13:00:00
3   2022-12-05 00:00:00
dtype: datetime64[ns]

漂浮

IIUC,你可以使用divmod (或numpy.modf )得到 integer 和小數部分,然后執行簡單的 boolean 算術:

s = pd.Series([7.15, 5.25, 22.30, 18.45])

s2, r = s.divmod(1)  # or np.modf(s)

s2[r.ge(0.3)] += 1

s2 = s2.astype(int)

備選方案:使用mod和 boolean 到 int 等價:

s2 = s.astype(int)+s.mod(1).ge(0.3)

output:

0     7
1     5
2    23
3    19
dtype: int64

注意精度。 由於浮點運算,比較浮點數並不總是那么容易。 例如,在 22.30 此處使用gt會失敗。 為確保精度先舍入到 2 位數字。

s.mod(1).round(2).ge(0.3)

或使用整數:

s.mod(1).mul(100).astype(int).ge(30)

這是一個使用時間戳的版本:

#dummy data:
df = pd.DataFrame({'time':pd.to_datetime([np.random.randint(0,10**8) for a in range(10)], unit='s')})


def custom_round(df, col, out):
    if df[col].minute >= 30:
        df[out] = df[col].ceil('H')
    else:
        df[out] = df[col].floor('H')
    return df


df.apply(lambda x: custom_round(x, 'time', 'new_time'), axis=1)

#編輯:

使用 numpy:

def custom_round(df, col, out):
    df[out] = np.where(
        (
            df['time'].dt.minute>=30), 
            df[col].dt.ceil('H'), 
            df[col].dt.floor('H')
    )
    return df
df = custom_round(df, 'time', 'new_time')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM