LoginSignup
0
1

More than 3 years have passed since last update.

DataFrameでマルチカラムの2段目だけを指定してデータを取得する方法

Posted at

概要

PandasのDataFrameでマルチカラムの2段目だけを指定してデータを取得する方法です。
下記のようなDataFrameの場合、2段目が「予算」の列だけ取得したいという場合を想定しています。

python
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(100, 10000, (6, 4)), 
                  columns = [
                      ['上期', '上期', '下期', '下期'], 
                      ['予算', '実績', '予算', '実績']
                  ], 
                  index = ['人件費', '減価償却費', '光熱費', '旅費交通費', '消耗品費', 'その他経費']
                 )
上期 下期
予算 実績 予算 実績
人件費 9611 8670 7938 4301
減価償却費 3696 6232 8410 1416
光熱費 8408 6698 4506 157
旅費交通費 8270 7533 9716 4732
消耗品費 4793 4894 962 8419
その他経費 6666 5125 6224 5593

方法

2段目だけ指定する場合は、pd.IndexSliceを使用します。
下記のように指定すると、2段目が「予算」の列を抽出できます。

python
df.loc[:, pd.IndexSlice[:, '予算']]
上期 下期
予算 予算
人件費 9611 7938
減価償却費 3696 8410
光熱費 8408 4506
旅費交通費 8270 9716
消耗品費 4793 962
その他経費 6666 6224
0
1
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
1