pandas:【基本】列の指定(Select句)


概要

  • データフレームから列を取り出す方法
    ※データの絞り込みではない
  • SQL文で言うとSelect句に該当するところ

前提

サンプルコード

列の取り出し(列名がある場合)

データ作成

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(15).reshape(3,5),columns=['a','b','c','d','e'])
print(df)
print(df.shape)
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
(3, 5)
  • 列名のあるデータ
  • データフレームのサイズは(3,5)
    • 一番左の列はインデックス列

1列指定

x = df['a']
y = df.a
print(x)
print(x.shape)
print(y)
print(y.shape)
0     0
1     5
2    10
Name: a, dtype: int64
(3,)
0     0
1     5
2    10
Name: a, dtype: int64
(3,)

複数列の指定

z = df[['b','d']] #2つ目
print(z)
print(z.shape)
    b   d
0   1   3
1   6   8
2  11  13
(3, 2)
  • 「b」列と「d」列が抽出された
  • ['b’,’d’]のようにリスト形式で指定する

列の取り出し(列名がない場合、列番号利用)

データ作成

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(15).reshape(3,5))
print(df)
print(df.shape)
    0   1   2   3   4
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
(3, 5)
  • 元のデータフレームは(3,5)のサイズ
    • 一番左の列はインデックス列
    • 列もインデックス列になっている

1列指定

x = df[0]
print(x)
print(x.shape)
0     0
1     5
2    10
Name: 0, dtype: int64
(3,)

複数列の指定

y = df[[1,3]]
print(y)
print(y.shape)
    1   3
0   1   3
1   6   8
2  11  13
(3, 2)
  • 列のインデックス番号が1と3が抽出された
  • [1,3]のようにリスト形式で指定する


Posted by futa