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

Python Pandas - 지정된 주파수에서 인덱스 값과 PeriodArray로 변환된 인덱스 간의 차이의 TimedeltaArray를 계산합니다.

<시간/>

지정된 주파수에서 인덱스 값과 PeriodArray로 변환된 인덱스 간의 차이의 TimedeltaArray를 계산하려면 datetimeindex.to_perioddelta()를 사용하세요. 방법. freq를 사용하여 주파수를 설정합니다. 매개변수.

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

import pandas as pd

기간이 7이고 빈도가 Y 즉 연도 −

인 DatetimeIndex를 만듭니다.
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')

DateTimeIndex 표시 -

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

인덱스 값과 PeriodArray로 변환된 인덱스의 차이의 TimedeltaArray를 계산합니다. 값이 'M' -

인 "freq" 매개변수를 사용하여 주기 주파수를 설정했습니다.
print("\nConvert DateTimeIndex to PeriodDelta...\n",
datetimeindex.to_perioddelta(freq='M'))

예시

다음은 코드입니다 -

import pandas as pd

# DatetimeIndex with period 7 and frequency as Y i.e. year
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')

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

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

# Convert DateTimeIndex to Period
# We have set the frequency as Month using the "freq" parameter with value 'M'
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))

# Calculate TimedeltaArray of difference between index values and index converted to PeriodArray
# We have set the Period frequency using the "freq" parameter with value 'M'
print("\nConvert DateTimeIndex to PeriodDelta...\n",
datetimeindex.to_perioddelta(freq='M'))
와 함께 "freq" 매개변수를 사용하여 기간 빈도를 설정했습니다.

출력

이것은 다음 코드를 생성합니다 -

DateTimeIndex...
DatetimeIndex(['2021-12-31 07:20:32.261811624',
'2023-12-31 07:20:32.261811624',
'2025-12-31 07:20:32.261811624',
'2027-12-31 07:20:32.261811624',
'2029-12-31 07:20:32.261811624'],
dtype='datetime64[ns]', freq='2A-DEC')
DateTimeIndex frequency...
<2 * YearEnds: month=12>

Convert DateTimeIndex to Period...
PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')

Convert DateTimeIndex to PeriodDelta...
TimedeltaIndex(['30 days 07:20:32.261811624', '30 days 07:20:32.261811624',
'30 days 07:20:32.261811624', '30 days 07:20:32.261811624',
'30 days 07:20:32.261811624'],
dtype='timedelta64[ns]', freq=None)