3
3

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 5 years have passed since last update.

groupby後の文字列連結

Last updated at Posted at 2019-06-27

毎回どうしても忘れてしまうのでメモ。

Dataframe中に入っている特定の列の値(カテゴリ、文字列とか)を、別の列の値でgroupbyした際にカンマ区切りでgroupby後の列に入れる方法。

dfが

列A 列B
A1 b1
A1 b2
A2 b3
A3 b4
A2 b5
A1 b6
A1 b7
A3 b8

である場合に、

df.groupby(‘列A’)

した際に

groupby後列A 列C
A1 b1,b2,b6,b7
A2 b3,b5
A3 b4,b8

とする方法↓

df.groupby('列A')[‘列B'].apply(lambda x: "%s" % ','.join(x))

列Bが数字(int,floatなど)であれば lambda式の部分を 

lambda x: "%s" % ','.join(str(x))

にすればOK

追記:下記の方法もあるとコメントもらいました。こっちが見やすくていいですね。

df.groupby('列A')['列B'].agg(','.join)
3
3
2

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?