0
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?

More than 1 year has passed since last update.

pandasでgroupレベルの情報にkey以外にcomment的な情報を付加する

Last updated at Posted at 2023-03-19

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

0
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
0
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?