pandasで時系列データをResamplingする際のaggregateメソッド:詳細解説とサンプルコード


pandas.core.resample.Resampler.aggregate は、時系列データの集計を行うためのメソッドです。Resampler オブジェクトに対して呼び出すことで、指定した周期でデータを集計し、新しい時系列データを作成することができます。

引数

  • **kwargs**: 集計関数に渡される追加の引数。

戻り値

Resampler オブジェクト。asfreq メソッドを使用して、集計結果を DataFrame として取得できます。

以下の例では、毎月の平均気温を計算します。

import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21]
}

df = pd.DataFrame(data)

# 毎月の平均気温を計算
resampled_df = df.resample("M").aggregate(mean="temperature")

# 結果の表示
print(resampled_df)

このコードを実行すると、以下の出力が得られます。

                temperature
date                         
2020-01-31    10.000000
2020-02-29    12.000000
2020-03-31    15.000000
2020-04-30    18.000000
2020-05-31    21.000000
  • aggregate メソッドは、列ごとに集計を行うため、DataFrame に対してのみ使用できます。Series に対して使用するには、apply メソッドを使用する必要があります。


例 1:複数の集計関数を使用した集計

この例では、毎月の平均気温と降水量を計算します。

import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21],
    "precipitation": [50, 42, 30, 60, 70]
}

df = pd.DataFrame(data)

# 毎月の平均気温と降水量を計算
resampled_df = df.resample("M").aggregate({"temperature": "mean", "precipitation": "sum"})

# 結果の表示
print(resampled_df)
                temperature  precipitation
date                         
2020-01-31    10.000000       50.000000
2020-02-29    12.000000       42.000000
2020-03-31    15.000000       30.000000
2020-04-30    18.000000       60.000000
2020-05-31    21.000000       70.000000

例 2:カスタム集計関数を使用した集計

この例では、各月の最大気温を計算するカスタム関数を作成します。

import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-01-15", "2020-01-31", "2020-02-01", "2020-02-15", "2020-02-29", "2020-03-01", "2020-03-15", "2020-03-31"]),
    "temperature": [10, 12, 15, 13, 14, 16, 15, 17, 18]
}

df = pd.DataFrame(data)

# 各月の最大気温を計算するカスタム関数
def max_temperature(series):
    return series.max()

# 毎月の最大気温を計算
resampled_df = df.resample("M").aggregate(temperature=max_temperature)

# 結果の表示
print(resampled_df)
                temperature
date                         
2020-01-31    15.000000
2020-02-29    16.000000
2020-03-31    18.000000

例 3:欠損値の処理

この例では、欠損値を置き換えてから集計を行います。

import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21],
    "precipitation": [50, 42, np.nan, 60, 70]  # 3月のみ欠損値
}

df = pd.DataFrame(data)

# 


apply メソッド

  • 欠点:
    • aggregate メソッドよりも処理速度が遅い場合がある。
    • コードが冗長になる可能性がある。
  • 利点:
    • より柔軟な集計が可能。
    • 関数だけでなく、lambda式やクラスインスタンスも使用できる。
import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21],
    "precipitation": [50, 42, 30, 60, 70]
}

df = pd.DataFrame(data)

# 毎月の平均気温と降水量を計算
def g(df):
    return df["temperature"].mean(), df["precipitation"].sum()

resampled_df = df.resample("M").apply(g)

# 結果の表示
print(resampled_df)

groupby と agg 関数

  • 欠点:
    • apply メソッドほど柔軟ではない。
  • 利点:
    • シンプルで分かりやすいコード。
    • aggregate メソッドよりも処理速度が速い場合がある。
import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21],
    "precipitation": [50, 42, 30, 60, 70]
}

df = pd.DataFrame(data)

# 毎月の平均気温と降水量を計算
resampled_df = df.resample("M").groupby("date").agg(mean_temperature=("temperature", "mean"), sum_precipitation=("precipitation", "sum"))

# 結果の表示
print(resampled_df)

ループ

  • 欠点:
    • コードが冗長で分かりにくい。
    • 処理速度が遅い。
  • 利点:
    • 非常に柔軟な方法。
    • 複雑な集計処理にも対応できる。
import pandas as pd

# データの準備
data = {
    "date": pd.to_datetime(["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01"]),
    "temperature": [10, 12, 15, 18, 21],
    "precipitation": [50, 42, 30, 60, 70]
}

df = pd.DataFrame(data)

# 毎月の平均気温と降水量を計算
monthly_results = []
for date in df["date"].dt.month_name().unique():
    monthly_df = df[df["date"].dt.month_name() == date]
    monthly_results.append((date, monthly_df["temperature"].mean(), monthly_df["precipitation"].sum()))

resampled_df = pd.DataFrame(monthly_results, columns=["month_name", "mean_temperature", "sum_precipitation"])

# 結果の表示
print(resampled_df)
  • 利点:
    • 大規模なデータセットを扱う場合に高速処理が可能。
    • データベースに保存されているデータに対して集計を行う場合に適している。