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

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


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

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

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 specific month from the PeriodIndex...\n", periodIndex.daysinmonth)

以下はコードです-

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 the month number i.e. 1 = January, 2 = February ... 12 = December
print("\nMonth number...\n", periodIndex.month)

# Display days in the specific month from the PeriodIndex object
print("\nDays of the specific month from the PeriodIndex...\n", periodIndex.daysinmonth)

出力

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

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>

Month number...
Int64Index([7, 10, 11, 9, 3, 6], dtype='int64')

Days of the specific month from the PeriodIndex...
Int64Index([31, 31, 30, 30, 31, 30], 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. Pythonで月の最後の日を取得するにはどうすればよいですか?

    カレンダーモジュールを使用して、月の最初の日の平日と月の日数を見つけることができます。この情報を使用すると、月の最終日を簡単に取得できます。 calenderモジュールには、指定された年と月の月の最初の日の平日と月の日数を返すメソッドmonthrange(year、month)があります。 例 import calendar day, num_days = calendar.monthrange(2017, 12) last_week = num_days % 7 last_day = (day + last_week) % 7 print(last_day) 出力 これにより出力が得られます