Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonパンダ-DateTimeIndexをPeriodに変換する方法


DateTimeIndexをPeriodに変換するには、 datetimeindex.to_period()を使用します パンダのメソッド。頻度は頻度を使用して設定されます パラメータ。

まず、必要なライブラリをインポートします-

import pandas as pd

期間5と頻度をY、つまり年としてDatetimeIndexを作成します-

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')

DateTimeIndexを表示-

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

DateTimeIndexをPeriodに変換します。値「M」-

の「freq」パラメータを使用して、頻度を月に設定しました。
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))

以下はコードです-

import pandas as pd

# DatetimeIndex with period 5 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'))

出力

これにより、次のコードが生成されます-

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]')

  1. パンダオフセットをPython日付に変換する方法は?

    日付オブジェクトからパンダを引くと、パンダのタイムスタンプオブジェクトが得られます。このオブジェクトは、文字列形式の日付またはDateオブジェクト(標準のPython日付)に変換できます。または、日時ライブラリのtimedeltaオブジェクトを使用できます。 例 from pandas.tseries.frequencies import to_offset import pandas as pd dt = pd.to_datetime('2018-01-04') - to_offset("5D") print(type(dt)) 出力 これにより、出力

  2. Pythonで文字列を辞書に変換する方法は?

    ここでast.literal_eval()を使用して、文字列をPython式として評価できます。式ノードまたはPython式を含む文字列を安全に評価します。提供される文字列またはノードは、文字列、数値、タプル、リスト、dict、ブール値、およびなしのPythonリテラル構造のみで構成されます。例:  >>>import ast >>>x = ast.literal_eval("{'foo' : 'bar', 'hello' : 'world'}") >>