Pandas group-by と Sum の集計を取得する方法

Asad Riaz 2023年1月30日 Pandas Pandas DataFrame
  1. groupby を使用した累積合計
  2. pivot() はデータを素敵なテーブルに再配置する
  3. Pandas の groupby に関数を適用する
  4. 列の合計を取得する agg()
Pandas group-by と Sum の集計を取得する方法

Pandas の groupbysum の集合を取得する方法を示します。また、pivot 機能を見て、データを素敵なテーブルに配置し、カスタム関数を定義して、DataFrame に適用して実行する方法も見ていきます。また、agg() を使用して総計を取得します。

groupby を使用した累積合計

groupby メソッドを使用して累積合計を取得できます。DateFruit、および Sale 列を持つ次の DataFrame を考えてみます。

import pandas as pd  df = pd.DataFrame(  {  "Date": ["08/09/2018", "10/09/2018", "08/09/2018", "10/09/2018"],  "Fruit": [  "Apple",  "Apple",  "Banana",  "Banana",  ],  "Sale": [34, 12, 22, 27],  } ) 

果物ごと、および日付ごとの販売の累積合計を計算する場合は、次のようにします。

import pandas as pd  df = pd.DataFrame(  {  "Date": ["08/09/2018", "10/09/2018", "08/09/2018", "10/09/2018"],  "Fruit": [  "Apple",  "Apple",  "Banana",  "Banana",  ],  "Sale": [34, 12, 22, 27],  } ) print(df.groupby(by=["Fruit", "Date"]).sum().groupby(level=[0]).cumsum()) 

出力:

Fruit Date Sale Apple 08/09/2018 34  10/09/2018 46 Banana 08/09/2018 22  10/09/2018 49 

pivot() はデータを素敵なテーブルに再配置する

pivot() メソッドはテーブルの行と列の属性を設定できます。上記のコードを変更し、pivot() メソッドを適用して、データを素敵なテーブルに再配置します。

import pandas as pd  df = pd.DataFrame(  {  "Date": ["08/09/2018", "10/09/2018", "08/09/2018", "10/09/2018"],  "Fruit": [  "Apple",  "Apple",  "Banana",  "Banana",  ],  "Sale": [34, 12, 22, 27],  } ) print(  df.groupby(["Fruit", "Date"], as_index=False).sum().pivot("Fruit", "Date").fillna(0) ) 

出力:

 Sale Date 08/09/2018 10/09/2018 Fruit Apple 34 12 Banana 22 27 

Pandas の groupby に関数を適用する

series または 1 次元配列の値のカウントを取得する簡単なメソッドを作成し、groupby を使用して各値の集計カウントを取得します。

from pandas import *  d = {"series": Series(["1", "2", "1", "1", "4", "4", "5"])} df = DataFrame(d)   def get_count(values):  return len(values)   grouped_count = df.groupby("series").series.agg(get_count) print(grouped_count) 

コードを実行すると、次の出力が得られます。これは、各値が連続して出現することを示しています。

出力:

series 1 3 2 1 4 2 5 1 Name: series, dtype: int64 

列の合計を取得する agg()

agg() を使用して、列に合計演算を適用できます。コード例:

import pandas as pd  df = pd.DataFrame(  {  "Date": ["08/09/2018", "10/09/2018", "08/09/2018", "10/09/2018"],  "Fruit": [  "Apple",  "Apple",  "Banana",  "Banana",  ],  "Sale": [34, 12, 22, 27],  } ) print(df.groupby(["Fruit"])["Sale"].agg("sum")) 

出力:

Fruit Apple 46 Banana 49 Name: Sale, dtype: int64 
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe

関連記事 - Pandas DataFrame