1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】pandasのDataFrameでgroupbyで合計した結果から上位の件数を指定して値取得

Posted at

## 概要
pandasのDataFrameで、ある項目でgroupbyした後にその合計値で上位のものを取得する実装をメモ書きします。

前提

  • 使用したpandasのバージョンは2.2.3です。

対応方針

実装サンプル

以下のサンプルを実行すると、group1: B value: 150group1: A value: 100が出力されます。

import pandas as pd

# サンプルデータの作成
df = pd.DataFrame(
    {
        "group1": ["A", "A", "B", "B", "C", "A", "D", "B", "E"],
        "group2": ["X", "Y", "X", "Y", "X", "S", "C", "A", "K"],
        "value": [10, 20, 30, 40, 50, 70, 70, 80, 9],
    }
)

# group1でgroupbyして上位2件を取得
grouped = df.groupby("group1")["value"].sum().nlargest(2)

# 対象のgroupとvalueを出力
for i, v in grouped.items():
    print("group1: ", i, "value: ", v)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?