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

Python Pandas - Trả lại số lượng gia số được áp dụng trên đối tượng DateOffset đã cho

Để trả về số lượng gia số được áp dụng trên đối tượng DateOffset đã cho, hãy sử dụng thuộc tính offset.n trong Pandas. Đầu tiên, hãy nhập các thư viện được yêu cầu -

from pandas.tseries.frequencies import to_offset
import pandas as pd

Đặt đối tượng dấu thời gian trong Pandas -

timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

Tạo DateOffset. Chúng tôi đang tăng các tháng ở đây bằng cách sử dụng tần suất "M" -

offset = to_offset("5M")

Hiển thị Dấu thời gian đã cập nhật -

print("\nUpdated Timestamp...\n",timestamp + offset)

Trả lại số lượng gia tăng trên đối tượng DateOffset đã cho -

print("\nThe count of increments on the DateOffset object..\n", offset.n)

Ví dụ

Sau đây là mã -

from pandas.tseries.frequencies import to_offset
import pandas as pd

# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

# Display the Timestamp
print("Timestamp...\n",timestamp)

# Create the DateOffset
# We are incrementing the months here using the "M" frequency
offset = to_offset("5M")

# Display the DateOffset
print("\nDateOffset...\n",offset)

# Display the Updated Timestamp
print("\nUpdated Timestamp...\n",timestamp + offset)

# return the count of increments on the given DateOffset object
print("\nThe count of increments on the DateOffset object..\n", offset.n)

Đầu ra

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

Timestamp...
 2021-09-26 03:25:02.000045

DateOffset...
 <5 * MonthEnds>

Updated Timestamp...
 2022-01-31 03:25:02.000045

The count of increments on the DateOffset object..
 5