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.

Pythonで「ピボットテーブルみたいなの書きたい」と思ったので、ChatGPTに聞いてみたら

Posted at

やりたいこと

PandasのDataframeでdf1を変形して、df_newのようなデータ構造にしたいんです。

df1 = pd.DataFrame(
    data={'区分': ['なし', 'S部', 'S部', 'S部', 'S部', 'G部', 'G部', 'G部', 'G部', 'その他', 'その他', 'その他'], 
          'State': ['初級', 'なし', '初級', '中級', '上級', 'なし', '初級', '上級', '事務局', 'なし', '初級', '中級'],
          'Size': [1, 12, 8, 125, 7, 5, 2, 4, 3, 26, 5, 9]}
)

df_new= pd.DataFrame(
    data=np.array([[  0,  1,   0,  0, 0],
                   [ 12,  8, 125,  7, 0],
                   [  5,  2,   0,  4, 3],
                   [ 26,  5,   9,  0, 0]]),
    index=['なし', 'S部', 'G部', 'その他'],
    columns=['なし', '初級', '中級', '上級', '事務局']
             )

ソリューション

例によって、ChatGPTに聞いたら、なんのことはない、「ピボットテーブル使え」と言われました。
相変わらず、秒で答えをくれるChatGPTさん。

Sample.py
import pandas as pd
import numpy as np

df1 = pd.DataFrame(
    data={'区分': ['なし', 'S部', 'S部', 'S部', 'S部', 'G部', 'G部', 'G部', 'G部', 'その他', 'その他', 'その他'], 
          'State': ['初級', 'なし', '初級', '中級', '上級', 'なし', '初級', '上級', '事務局', 'なし', '初級', '中級'],
          'Size': [1, 12, 8, 125, 7, 5, 2, 4, 3, 26, 5, 9]}
)

df_new = df1.pivot_table(index='区分', columns='State', values='Size', aggfunc='sum', fill_value=0)

print(df_new)

めっちゃ簡単やん…と思いました。

(おわり)

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?