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のgroupbyに関する基本の処理について

Posted at

#1. この記事について

メモ的な形でpandasのgroupbyの基本的な操作のおさらいをします.

#2. 課題設定 :
以下のdataframe aに対して,操作Aの操作を加えてdataframeを作成せよ:

import pandas as pd
a = pd.DataFrame([["a",1,2,"A"],["a",2,4,"A"],["b",3,6,"B"]],columns = ["w","x","y","z"])
  • 操作A :
    • wの値が同じものに関して,
      1. xに関しては合計を
      2. yに対しては平均と分散を
      3. zに対してはそのままの値を
      4. wのの長さを加えて集約せよ.

3. データ確認

image.png

4. 問題理解

  • まず,zwごとに値が異なるためそれぞれの集約として考えることができる.
  • すなわち,基本的に以下の操作で完結する:
a.groupby(["w","z"]).hogehoge

5. 答えの例

以下の操作を加えることで,操作が完結する:

# 1. xの合計
q1 = a.groupby(["w","z"])["x"].sum().reset_index().rename(columns={"x":"x_sum"})

# 2. yの平均と分散
q2a = a.groupby(["w","z"])["y"].mean().reset_index().rename(columns={"y":"y_mean"})
q2b = a.groupby(["w","z"])["y"].std().reset_index().rename(columns={"y":"y_std"}).fillna(0)
q2 = pd.merge(q2a,q2b)

# 3. それぞれの長さ
q3 = a.groupby(["w","z"]).size().reset_index().rename(columns = {0:"length"})

# マージを行う
res_df = q1
lst = [q2,q3]
for i in lst:
    res_df = pd.merge(res_df,i)
res_df.head()

image.png

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