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

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


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

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

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オブジェクトから曜日を表示します。曜日は、Monday =0、Tuesday =1 ... Sunday =6 −

として表示されます。
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

以下はコードです-

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 week from the PeriodIndex object
# Days of week are displayed as Monday=0, Tuesday=1 ... Sunday=6
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

出力

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

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 week from the PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')

  1. 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

  2. Python Pandas –データ型とDataFrame列の情報を取得します

    データ型とDataFrame列の情報を取得するには、info()メソッドを使用します。必要なライブラリをエイリアスでインポートします- import pandas as pd; 3列のデータフレームを作成する- dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'