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

Python PandasPeriodIndex-PeriodArrayを指定された頻度に変換します


PeriodArrayを指定された頻度に変換するには、 periodIndex.asfreq()を使用します メソッド。

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

import pandas as pd

PeriodIndexオブジェクトを作成します-

periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2020-07-15 02:55:15', '2022-06-25 09:40:55'], freq="Y")

PeriodIndexオブジェクトを表示-

print("PeriodIndex...\n", periodIndex)

指定された周波数に変換します。 asfreq()のパラメータとして周波数を設定しました-

print("\nConvert..\n", periodIndex.asfreq('M'))

以下はコードです-

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2020-07-15 02:55:15', '2022-06-25 09:40:55'], freq="Y")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency object...\n", periodIndex.freq)

# Display PeriodIndex frequency as string
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)

# Convert to the specified frequency
# We have set the frequency as the parameter of the asfreq()
print("\nConvert..\n", periodIndex.asfreq('M'))

出力

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

PeriodIndex...
PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]')

PeriodIndex frequency object...
<YearEnd: month=12>

PeriodIndex frequency object as a string...
A-DEC

Convert..
PeriodIndex(['2021-12', '2019-12', '2020-12', '2022-12'], dtype='period[M]')

  1. Pythonパンダ-1時間ごとの頻度でTimedeltaを丸める

    指定された解像度でTimedeltaを丸めるには、 timestamp.round()を使用します 方法。値Hのfreqパラメータを使用して、1時間ごとの周波数分解能を設定します。 まず、必要なライブラリをインポートします- import pandas as pd TimeDeltasは、Pythonの標準の日時ライブラリであり、異なる表現のtimedeltaを使用します。 Timedeltaオブジェクトを作成する timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns') タイムデルタを表示する

  2. PythonPandas-指定された解像度でTimedeltaを丸めます

    指定された解像度でTimedeltaを丸めるには、 timestamp.round()を使用します 方法。 freqパラメータを使用して解像度を設定します。 まず、必要なライブラリをインポートします- import pandas as pd Timedeltaオブジェクトを作成する timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns') タイムデルタを表示する print("Timedelta...\n", timedelta) 秒の頻度で丸められたタイムスタンプを返しま