LoginSignup
4
7

More than 5 years have passed since last update.

pandas 特定の文字を含む列の名称を取ってくる

Last updated at Posted at 2017-09-10

pandas 特定の文字を含む列の名称を取ってくる

この記事ではpandas 0.19.2を利用しています。

はじめに


データ型の変換や、解析を行なう上で変数を整理したりなどで、
意に沿ったかたちで列名称を取ってきたいケースは意外と多いと思います。

方法はいろいろあると思うのですが、ここではfindを利用してます。

データ


# coding:utf-8

df = pd.DataFrame(
    {'id':['1001','1002','1003','1004'],
      'x01':[3,2,3,1],
      'x02':[1,2,1,1],
      'y01':[3,2,2,2],
      'y02':[1,1,1,2],
      'z01':[1,2,3,3],
     })

df
id x01 x02 y01 y02 z01
0 1001 3 1 3 1 1
1 1002 2 2 2 1 2
2 1003 3 1 2 1 3
3 1004 1 1 2 2 3

findを利用して特定の文字を含む列名称を取得


リスト内包表記とfindを利用して、条件に合うものを取得します。
関数 find は、その文字が最初に現れる位置を返します。なかった場合には -1 を返します。
ここでは'y'を含む変数を取ってきたいとします。

temp_col = [item for item in df.columns if item.find('y') != -1]

print temp_col
['y01', 'y02']

OR を使って以下のようにもできます。

temp_col_2 = [item for item in df.columns if item.find('y') != -1 or item.find('z') != -1]

print temp_col_2
['y01', 'y02', 'z01']

取得したリストを使って、以下のように特定の列に絞ったデータを取得できます。

df[['id'] + temp_col]
id y01 y02
0 1001 3 1
1 1002 2 2
2 1003 3 1
3 1004 1 1
4
7
3

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