LoginSignup
8
1

More than 5 years have passed since last update.

pandasのDataFrameでargmaxの集計をしたい時

Last updated at Posted at 2018-02-01

pandasのDataFrameを使って、argmaxを集計したいとき、どのようにすれば良いか。

これを1発でやる関数がpandasには備わっています。それは、idxmax関数です。

例えば、以下のようなデータで、各列について、最大値をとるindex番号が欲しいとする。

0 1 2 3 4 5 6 7 8 9
0 0.189460 0.086207 0.203066 0.208812 0.259933 0.185123 0.158537 0.200099 0.149425 0.138298
1 0.209651 0.256466 0.238045 0.132184 0.134794 0.230882 0.208426 0.211899 0.272578 0.328267
2 0.196588 0.153017 0.171099 0.270115 0.205347 0.157334 0.216741 0.185818 0.182266 0.177812
3 0.215362 0.321121 0.190227 0.195402 0.157817 0.177183 0.161308 0.219288 0.177340 0.200608
4 0.188939 0.183190 0.197563 0.193487 0.242109 0.249478 0.254989 0.182896 0.218391 0.155015

これは以下のようにすれば、一発!

>> df = pd.DataFrame('hogehoge')
>> df.idxmax()

すると、以下のような結果になります。

0     3
1     3
2     1
3     2
4     0
5     4
6     4
7     3
8     1
9     1
dtype: int64

ちなみに返り値のデータ型は、Seiresです。

>> type(df.idxmax())
<class 'pandas.core.series.Series'>

参考

8
1
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
8
1