Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas - 기간을 원하는 빈도로 변환

<시간/>

주기를 원하는 빈도로 변환하려면 period.asfreq()를 사용하세요. 방법. 'H' 지정자를 사용하여 원하는 시간별 빈도로 설정한다고 가정해 보겠습니다.

먼저 필요한 라이브러리를 가져옵니다 -

import pandas as pd

pandas.Period는 기간을 나타냅니다. 두 개의 기간 개체 만들기

period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

기간 개체 표시

print("Period1...\n", period1)
print("Period2...\n", period2)

주기를 원하는 주파수로 변환합니다. 빈도를 H, 즉 시간별 빈도로 설정했습니다.

res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

예시

다음은 코드입니다.

import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# Convert Period to desired frequency
# We have set frequency as H i.e. Hourly frequency
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

# Return the year from the two Period objects
print("\nResult after conversion from the 1st Period object ...\n", res1)
print("\nResult after conversion from the 2nd Period object...\n", res2)

출력

그러면 다음 코드가 생성됩니다.

Period1...
2020-09-23 03:15:40
Period2...
2021-04-16

Result after conversion from the 1st Period object ...
2020-09-23 03:00

Result after conversion from the 2nd Period object...
2021-04-16 23:00