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

Python pandas入門:DateTimeIndexのis_leap_yearで日付がうるう年かどうかを判定する方法

pandasのDateTimeIndex.is_leap_yearプロパティを使用すると、DateTimeIndexに含まれる日付がうるう年に属しているかどうかを簡単に確認できます。このプロパティは、各日付に対してうるう年であればTrue、そうでなければFalseを要素とするブール値の配列を返します。

必要なライブラリのインポート

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

import pandas as pd

DatetimeIndexの作成

次に、期間6・頻度3年(3Y)・タイムゾーン「Australia/Adelaide」を指定してDatetimeIndexを作成します。

datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='3Y')

作成したDatetimeIndexを表示してみましょう。

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

さらに、DatetimeIndexの頻度も確認しておきます。

print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

うるう年かどうかの判定

is_leap_yearプロパティを使って、DateTimeIndex内の各日付がうるう年に属しているかどうかをチェックします。

print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

完全なサンプルコード

以下に、ここまでの手順をまとめたコード全体を示します。

import pandas as pd

# 期間6・頻度3年のDatetimeIndexを作成
# タイムゾーンは Australia/Adelaide を指定
datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='3Y')

# DatetimeIndexを表示
print("DateTimeIndex...\n", datetimeindex)

# DatetimeIndexの頻度を表示
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# 各日付がうるう年に属しているかどうかを判定
print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

実行結果

上記のコードを実行すると、次のような出力が得られます。

DateTimeIndex...
DatetimeIndex(['2021-12-31 02:30:50+10:30', '2024-12-31 02:30:50+10:30',
'2027-12-31 02:30:50+10:30', '2030-12-31 02:30:50+10:30',
'2033-12-31 02:30:50+10:30', '2036-12-31 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='3A-DEC')
DateTimeIndex frequency...
<3 * YearEnds: month=12>

Check whether the date in DateTimeIndex belongs to a leap year or not...
[False True False False False True]

実行結果の解説

出力結果を見ると、2024年と2036年がうるう年であるため、対応する位置の値がTrueになっていることがわかります。それ以外の年(2021年・2027年・2030年・2033年)は平年なのでFalseが返されています。このように、is_leap_yearプロパティを使えば、時系列データの中からうるう年に該当する日付を簡単に抽出・判定できます。

  1. 【Pandas入門】DateTimeIndexから頻度(freq)を抽出する方法

    Pandasで日時インデックス(DateTimeIndex)から頻度を抽出するには、DateTimeIndex.freq プロパティを使用します。この記事では、実際のコード例を通じて、その使い方をわかりやすく解説します。 必要なライブラリのインポート まず、必要なライブラリをインポートします。 import pandas as pd DateTimeIndexの作成 次に、期間6・頻度「D」(日単位)でDatetimeIndexを作成します。タイムゾーンはオーストラリアのアデレード(Australia/Adelaide)を指定します。 datetimeindex = pd.date_ran

  2. Python Pandas – Periodオブジェクトからその年がうるう年かどうかを確認する方法

    Periodオブジェクトから、その年がうるう年(閏年)かどうかを確認するには、period.is_leap_year プロパティを使用します。このプロパティは、Periodオブジェクトが属する年がうるう年であれば True、そうでなければ False を返します。まず、必要なライブラリをインポートしましょう。import pandas as pdpandas.Period は、一定の期間(時点)を表すオブジェクトです。ここでは、2つのPeriodオブジェクトを作成します。period1 = pd.Period("2020-09-23 05:55:30") period2 =