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

【Python Pandas】TimedeltaIndexから各要素の日数(days)を抽出する方法

TimedeltaIndexオブジェクトから各要素の日数を抽出するには、TimedeltaIndex.daysプロパティを使用します。このプロパティは、各timedelta要素に含まれる「日」の部分を整数値(int64)として返します。時間や分などの情報は無視され、純粋な日数のみが取得できる点が特徴です。

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

まず、pandasをインポートします。

import pandas as pd

TimedeltaIndexオブジェクトの作成

次に、TimedeltaIndexオブジェクトを作成します。「data」パラメータを使って、timedelta形式の文字列データを設定しています。

tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])

TimedeltaIndexの表示

作成したTimedeltaIndexを確認してみましょう。

print("TimedeltaIndex...\n", tdIndex)

各要素から日数を抽出して表示

daysプロパティにアクセスすることで、TimedeltaIndexの各要素から日数を取得できます。

print("\nThe number of days from the TimeDeltaIndex object...\n", tdIndex.days)

完全なサンプルコード

以下は、ここまでの手順をまとめたコード全体です。あわせて、TimeDeltaの構成要素(日・時・分・秒など)をデータフレーム形式で返すcomponentsプロパティも使用しています。

import pandas as pd

# TimedeltaIndexオブジェクトを作成
# 「data」パラメータでtimedelta形式のデータを設定
tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])

# TimedeltaIndexを表示
print("TimedeltaIndex...\n", tdIndex)

# 各要素から日数を抽出して表示
print("\nThe number of days from the TimeDeltaIndex object...\n", tdIndex.days)

# TimeDeltaの構成要素をデータフレームとして返す
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)

実行結果

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

TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 21:15:45.999999'],
dtype='timedelta64[ns]', freq=None)

The number of days from the TimeDeltaIndex object...
Int64Index([10, 0, 2, 0], dtype='int64')

The Dataframe of the components of TimeDeltas...
      days hours minutes seconds milliseconds microseconds nanoseconds
 0    10    5       2       0        0            3           10
 1     0   22      39      19      999          999            0
 2     2    7       8       2        0           45            0
 3     0   21      15      45      999          999            0

ポイントのまとめ

  • tdIndex.days:各要素の「日」の部分だけをint64型のインデックスとして返します。例えば「10 days 05:02:00」なら10、「0 days 22:39:19」なら0となります。
  • tdIndex.components:日・時・分・秒・ミリ秒・マイクロ秒・ナノ秒に分解した結果をデータフレームで取得できます。より詳細な内訳が必要な場合に便利です。

期間データを扱う際に、日数単位での集計やフィルタリングを行いたいケースでは、daysプロパティが非常に役立ちます。

  1. Python Pandas – グループごとの行数を数える方法

    グループごとの行数を数える方法 Pandasで各グループに含まれる行数を数えるには、group.size()を使用します。まず、必要なライブラリをインポートしましょう。 import pandas as pd 続いて、サンプル用のDataFrameを作成します。 dataFrame = pd.DataFrame({ Product Category: [Computer, Mobile Phone, Electronics, Electronics, Computer, Mobile Phone], Quantity: [10, 50, 10, 20, 25, 50], Pr

  2. Pythonでリスト内の各要素の出現回数をサブリストとして作成する方法

    Pythonでは、数値を要素とするリストを扱う際に、同じ値が複数回出現することがよくあります。この記事では、リスト内の各要素とその出現回数(頻度)をペアにしたサブリストを作成する方法を、2つのアプローチで解説します。 方法1:forループとappendを使う まずは基本的な方法です。リスト内の各要素について、それ以降のすべての要素と比較し、一致するものがあればカウントを増やしていきます。最終的に「要素」と「その出現回数」を組み合わせたサブリストのリストを作成します。 コード例 def occurrences(list_in): result = [] checked = []