LoginSignup
9
5

More than 3 years have passed since last update.

pandas v1のgroupbyで複数の統計量を取得したい場合

Posted at

概要

pandasのgroupbyで1つのカラムに複数の関数を適用させるためにdict形式でagg()の引数を与えていたが、v1でその機能が削除されてしまっていたため、使用できなくなった。その解決方法。
データはpandasのドキュメントにあったものを利用しています。

データ

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                                 'height': [9.1, 6.0, 9.5, 34.0],
                                 'weight': [7.9, 7.5, 9.9, 198.0]})

スクリーンショット 2020-02-23 0.59.20.png

今回やろうとした処理とエラー

# kindごとに、heightの合計値と件数を集計し、それぞれ"sum_all", "count_all"という名前にする
animals.groupby("kind")["height"].agg({"sum_all":"sum", "count_all":"count"})
  • 想定していた出力(v1になる前はできてた)
    スクリーンショット 2020-02-23 1.05.00.png

  • 実際の出力

SpecificationError: nested renamer is not supported

何が原因だったか

Removed support for nested renaming in DataFrame.aggregate(), Series.aggregate(), core.groupby.DataFrameGroupBy.aggregate(), core.groupby.SeriesGroupBy.aggregate(), core.window.rolling.Rolling.aggregate() (GH18529)

解決方法

  • 集約とrenameを同時に行っていることが問題なので、それを分ければ良い
animals.groupby("kind")["height"].agg(["sum", "count"])
                                 .rename(columns={"sum": "sum_all", 
                                                  "count":"count_all"})
animals.groupby("kind")["height"].agg(sum_all="sum",
                                      count_all="count")
  • (参考)カラムをしていない状態でのNamed Aggrecationだと以下のような書き方になる
    • この書き方だとどの変数に対して集約するか指定できるのでわかりやすい
animals.groupby("kind").agg(sum_all=("height", "sum"),
                            count_all=("height", "count"))

参考

9
5
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
9
5