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

Python Pandas-PeriodIndexオブジェクトをTimestampに変換し、頻度を設定します


PeriodIndexオブジェクトをTimestampに変換するには、 PeriodIndex.to_timestamp()を使用します 方法。 freqを使用して頻度を設定します パラメータ。

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

import pandas as pd

PeriodIndexオブジェクトを作成します。 PeriodIndexは、一定の期間を示す順序値を保持する不変のndarrayです。 「freq」パラメータを使用して周波数を設定しました-

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)

PeriodIndexをタイムスタンプに変換します。 「freq」パラメータを使用して周波数を設定しました-

print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp(freq='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 PeriodIndex to timestamp
# We have set the frequency using the "freq" parameter
print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp(freq='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

PeriodIndex object to timestamp...
DatetimeIndex(['2021-01-31', '2019-01-31', '2020-01-31', '2022-01-31'], dtype='datetime64[ns]', freq=None)

  1. Pandas-TimestampオブジェクトをネイティブのPython日時オブジェクトに変換します

    TimestampオブジェクトをネイティブのPythondatetimeオブジェクトに変換するには、timestamp.to_pydatetime()メソッドを使用します。 まず、必要なライブラリをインポートします- import pandas as pd パンダでタイムスタンプオブジェクトを作成します timestamp = pd.Timestamp('2021-09-11T13:12:34.261811') タイムスタンプをネイティブPython日時オブジェクトに変換する timestamp.to_pydatetime() 例 以下はコードです import p

  2. PythonPandas-指定されたタイムスタンプを毎月の頻度で期間に変換します

    指定されたタイムスタンプを期間に変換するには、タイムスタンプ.to_period()を使用します 方法。その中で、 freqを使用して頻度を設定します パラメータ。月次頻度の場合、頻度をMに設定します。 まず、必要なライブラリをインポートします- import pandas as pd パンダでタイムスタンプオブジェクトを設定します timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33) タイムスタンプを期間に変換します。値が「M」の「freq」パラメータを使用して、頻度を月次として設定しました timestamp.to_period