Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@haru1977

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

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

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

### はじめに

データ型の変換や、解析を行なう上で変数を整理したりなどで、

### データ

``````# 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を利用して、条件に合うものを取得します。

ここでは'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
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
7
Help us understand the problem. What are the problem?