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

Python Pandas - Cách thực hiện thao tác sàn trên DateTimeIndex với tần suất hàng giờ

Để thực hiện hoạt động sàn trên DateTimeIndex với tần suất hàng giờ, hãy sử dụng DateTimeIndex.floor () phương pháp. Đối với tần suất hàng giờ, hãy sử dụng tần suất tham số có giá trị ‘H’ .

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

import pandas as pd

Tạo một DatetimeIndex với khoảng thời gian 5 và tần suất là phút tối thiểu -

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

Hiển thị DateTimeInde -

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

Hoạt động của sàn vào ngày DateTimeIndex với tần suất hàng giờ, Đối với tần suất hàng giờ, chúng tôi đã sử dụng 'H' -

print("\nPerforming floor operation with hourly frequency...\n",
datetimeindex.floor(freq='H'))

Ví dụ

Sau đây là mã -

import pandas as pd

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

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

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

# Floor operation on DateTimeIndex date with hourly frequency
# For hourly frequency, we have used 'H'
print("\nPerforming floor operation with hourly frequency...\n",
datetimeindex.floor(freq='H'))

Đầ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 07:40:32.261811624+09:30',
'2021-09-29 08:00:32.261811624+09:30',
'2021-09-29 08:20:32.261811624+09:30',
'2021-09-29 08:40:32.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='20T')
DateTimeIndex frequency...
<20 * Minutes>

Performing floor operation with hourly frequency...
DatetimeIndex(['2021-09-29 07:00:00+09:30', '2021-09-29 07:00:00+09:30',
'2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30',
'2021-09-29 08:00:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)