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

Python Pandas-PeriodIndexを作成し、その年の日を取得します


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

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

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("\nDays of the year from the PeriodIndex...\n", periodIndex.dayofyear)

以下はコードです-

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)
# Display day of the year from the PeriodIndex object
print("\nDays of the year from the PeriodIndex...\n", periodIndex.dayofyear)

出力

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

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

Days of the year from the PeriodIndex...
Int64Index([206, 303, 325, 258, 71, 169], dtype='int64')

  1. PythonPandas-Timestampオブジェクトから現在の日付と時刻を取得します

    Timestampオブジェクトから現在の日付と時刻を取得し、 timestamp.today()を使用します メソッド。 まず、必要なライブラリをインポートします- import pandas as pd import datetime パンダでタイムスタンプを作成する timestamp = pd.Timestamp(datetime.datetime(2021, 10, 10)) タイムスタンプを表示する print("Timestamp: ", timestamp) 現在の日付と時刻を取得する res = timestamp.today() 例 以下はコ

  2. Pythonの年間最優秀日

    「YYYY-MM-DD」の形式の日付があるとします。その年の日数を返す必要があります。したがって、日付が「2019-02-10」の場合、これは1年の41日目です。 これを解決するには、次の手順に従います- Dが[0、31、28、31、30、31、30、31、31、30、31、30、31]のような日数の配列であるとします 日付を年、月、日のリストに変換します 年がうるう年の場合は、日付D [2]=29を設定します 月mm–1までの日数とそれ以降の日数を合計します。 例 理解を深めるために、次の実装を見てみましょう- class Solution(object):   &nbs