Pandasのgroupbyには、グループごとにコメントやラベルなどの情報を付加する機能はありませんが、groupbyオブジェクト自体に任意の属性を追加することは可能です。
例えば、以下のようにgroupbyオブジェクトにcomment属性を追加し、グループごとにコメントを保存することができます。(とChatGPTが申しておりました)
サンプルコード
import pandas as pd
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
grouped = df.groupby('A')
# groupbyオブジェクトにcomment属性を追加
grouped.comment = {'foo': 'This is the group of "foo".', 'bar': 'This is the group of "bar".'}
# グループごとにコメントを表示
for key, group in grouped:
print(f"Group name: {key}")
print(f"Comment: {grouped.comment[key]}")
print(group)
結果
Group name: bar
Comment: This is the group of "bar".
A B C D
1 bar one 2 20
3 bar three 4 40
5 bar two 6 60
Group name: foo
Comment: This is the group of "foo".
A B C D
0 foo one 1 10
2 foo two 3 30
4 foo two 5 50
6 foo one 7 70
7 foo three 8 80
ここでは、grouped.comment属性に、各グループに対するコメントを格納しています。そして、forループで各グループのコメントを表示しています。この方法を使えば、groupbyオブジェクトに任意の属性を追加し、グループごとに情報を保存することができます。
以上 chatGPTに質問した結果を検証後転記したものです。
恐ろしい ChatGPT