MOB-LOG

モブおじの記録 (Programming, 統計・機械学習)

Q. pandas.Dataframe.query で”column==max(column)”を求めたい。A.「@で変数を参照できる。」

TL; DR

df内のある列column について、columnが最大の行を取ってきたい。pandas.DataFrame.queryで@参照をしたら簡単に求められる。(公式ドキュメント読むの重要だね)

vmax = df.column.max()
df.query("column == @vmax")

(とはいえ↓で済むので1行で済むこっちの方がいい気が...)

df[df.column == max(df.column)] # これ
df.iloc[df.column.argmax()] # もしくはこれ

やりたかったこと

「列 column 中で最大の値を持つ行を取得したい」例えば、

df = pd.DataFrame(data= {"column":range(10)})
df[df.column == max(df.column)] # これ
df.iloc[df.column.argmax()] # もしくはこれ

ただ、queryでやりたい。なぜならqueryの方がわかりやすそうだから(わがまま)。(1行でできるなら別によくね、とも思うけど、なんかわかりづらい)

直感的には df.query(”column == max(column)”) だけども、ValueError: "max" is not a supported functionが返ってきて思い通りにできない。

Google search や公式ドキュメント内で検索してもpandas.DataFrame.max の説明ばかり出てきて役に立たなかった(敗北)。

https://chat.openai.com/のGPT-3.5君に聞いてみた(質問の英語はなんとなくおかしい)。

OpenAIのChatGPT3.5君に聞いてみた。正直完璧な答え。

完璧や。人間の敗北。検索エンジンが役に立たなかった時のリファレンスとしてLLM君らが役に立ちすぎている。。。 (公式ドキュメントのqueryのページ には2行目に変数の使用については書いてあるので、変数の参照についてを知っていれば今回の方法にたどりつけた問題だった。)

ChatGPT君が答えられたってことは、どこかBlogやらオープンなドキュメントで述べられているはず、という話で、「queryの中でどうやってmaxみたいな関数を使うの?」というニュアンスで探しても見つけられなかった。おそらくどこかで誰かが述べているんだと思うけど、自分は見つけられなかった。

ともあれLLMを検索エンジンとして使うの有益だった。 2行になるので優位とは言えないけど、pandas.DataFrame.queryのクエリ内で@を使って変数を参照することがわかって満足。max程度ならqueryじゃなくともいいけど、いつかどこかで使いどころがあるはず。

全文

To find a record that has the maximum number of a specific column, such as "epoch," using the query method in pandas DataFrame, you can't directly use the max() function within the query string. Instead, you can calculate the maximum value separately and then use it in the query.

Here's an example of how you can accomplish this:

import pandas as pd

# Assuming you have a DataFrame named 'df' with a column named 'epoch'

# Calculate the maximum value of the 'epoch' column
max_epoch = df['epoch'].max()

# Use the calculated maximum value in the query
result = df.query("epoch == @max_epoch")

In the above code, max_epoch stores the maximum value from the 'epoch' column using the max() function. Then, in the query string, @max_epoch is used to reference the calculated maximum value.

Note the use of the @ symbol before the variable name (max_epoch) within the query string. This is necessary to indicate that you are referencing a Python variable inside the query string.

By doing this, you will filter the DataFrame (df) to only include the records where the 'epoch' column value matches the maximum value calculated. The result will be stored in the result variable.

結論

ChatGPT君 > ヒト

はっきりわかんだね。

戒め「公式ドキュメント読め」