Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Làm tròn một DateTimeIndex với tần suất là bội số của một đơn vị

Để làm tròn DateTimeIndex với tần suất là bội số của một đơn vị, hãy sử dụng DateTimeIndex.round () phương pháp. Đặt tần suất tham số cho tần số.

Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

DatetimeIndex với khoảng thời gian 5 và tần suất là H tức là giờ -

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='H')

Hiển thị DateTimeIndex -

print("DateTimeIndex...\n", datetimeindex)

Làm tròn một DateTimeIndex với tần suất 10 phút, tức là bội số của một đơn vị. Đối với tần suất phút, chúng tôi đã sử dụng 'T -

print("\nPerforming round operation with multiples of a single unit frequency...\n",
datetimeindex.round(freq='10T'))

Ví dụ

Sau đây là mã -

import pandas as pd

# DatetimeIndex with period 5 and frequency as H i.e. hours
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='H')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# Round a DateTimeIndex with 10 minutes frequency i.e. multiples of a single unit
# For minutes frequency, we have used 'T'
print("\nPerforming round operation with multiples of a single unit frequency...\n",
datetimeindex.round(freq='10T'))

Đầu ra

Điều này sẽ tạo ra mã sau -

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30',
'2021-09-29 08:20:32.261811624+09:30',
'2021-09-29 09:20:32.261811624+09:30',
'2021-09-29 10:20:32.261811624+09:30',
'2021-09-29 11:20:32.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='H')
DateTimeIndex frequency...
<Hour>

Performing round operation with multiples of a single unit frequency...
DatetimeIndex(['2021-09-29 07:20:00+09:30', '2021-09-29 08:20:00+09:30',
'2021-09-29 09:20:00+09:30', '2021-09-29 10:20:00+09:30',
'2021-09-29 11:20:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)