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

Python Pandas-PeriodIndexを作成し、期間の日数を取得します


PeriodIndexを作成するには、 pandas.PeriodIndex()を使用します 方法。 PeriodIndex.dayを使用して期間の日数を取得します プロパティ。

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

import pandas as pd

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

periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

PeriodIndexオブジェクトを表示-

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

PeriodIndexオブジェクトから日を表示-

print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

以下はコードです-

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(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

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

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

# Display day from the PeriodIndex object
print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

出力

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

PeriodIndex...
PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'],
dtype='period[D]')

PeriodIndex frequency...
<Day>

The number of days from the PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')

  1. PythonPandas-生理が始まる月の日を取得します

    期間が該当する月の日を取得するには、 period.dayを使用します プロパティ。 まず、必要なライブラリをインポートします- import pandas as pd pandas.Periodは期間を表します。 2つのPeriodオブジェクトの作成- period1 = pd.Period("2021-09-18") period2 = pd.Period(freq ='D', year = 2021, month = 9, day = 22, hour = 4, minute = 55) 2つのPeriodオブジェクトから月の日を取得します- r

  2. PythonPandas-TimeDeltaから日数を取得します

    TimeDeltaから日数を取得するには、 timedelta.daysを使用します パンダのプロパティ。まず、必要なライブラリをインポートします- import pandas as pd TimeDeltasは、Pythonの標準の日時ライブラリであり、異なる表現のtimedeltaを使用します。 Timedeltaオブジェクトを作成する timedelta = pd.Timedelta('5 days 1 min 45 s') 日数を返す timedelta.days 例 以下はコードです import pandas as pd # TimeDeltas is