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

Python Pandas入門:TimeDeltaIndexから各要素の「秒」成分を抽出する方法

PandasのTimedeltaIndexオブジェクトから各要素の「秒」の値を抽出したい場合は、TimedeltaIndex.secondsプロパティを使用します。この記事では、実際のコード例とともに、その使い方をわかりやすく解説します。

TimedeltaIndex.secondsプロパティとは

.secondsプロパティは、各timedelta要素に含まれる時間・分・秒のうち、「秒」の成分(0〜86399の範囲)を整数値として返します。注意点として、日数(days)は含まれないため、合計秒数を取得したい場合は別途total_seconds()メソッドを使う必要があります。

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

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

import pandas as pd

TimeDeltaIndexオブジェクトの作成

次に、dataパラメータにtimedelta形式の文字列を渡して、TimedeltaIndexオブジェクトを作成します。

tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 35s 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 seconds from the TimeDeltaIndex object...\n", tdIndex.seconds)

完全なサンプルコード

以下が実行コード全体です。あわせて、timedeltaの構成要素(日・時・分・秒など)をDataFrame形式で確認できるcomponentsも出力しています。

import pandas as pd

# TimeDeltaIndexオブジェクトを作成
# dataパラメータでtimedelta形式のデータを指定
tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 35s 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 seconds from the TimeDeltaIndex object...\n", tdIndex.seconds)

# timedeltaの構成要素をDataFrameとして返す
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)

実行結果

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

TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:35.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 seconds from the TimeDeltaIndex object...
Int64Index([18155, 81559, 25682, 76545], dtype='int64')

The Dataframe of the components of TimeDeltas...
    days    hours minutes seconds milliseconds microseconds nanoseconds
0     10      5       2      35        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

結果の読み方のポイント

出力された秒数の意味を確認してみましょう。たとえば最初の要素「10 days 05:02:35」の場合、.seconds18155を返します。これは「5時間 × 3600 + 2分 × 60 + 35秒 = 18155秒」と計算でき、日数部分(10日)は含まれていないことがわかります。

もし日数も含めた合計秒数が必要な場合は、次のようにtotal_seconds()を使用してください。

# 日数を含む合計秒数を取得する場合
total = tdIndex.total_seconds()
print(total)

このように、.secondstotal_seconds()を使い分けることで、時系列データや処理時間の分析を柔軟に行えます。

  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 = []