LoginSignup
0
2

More than 1 year has passed since last update.

【Pandas】列名に任意の文字列を含む列のみを抽出する

Last updated at Posted at 2021-03-31

備忘録として

例としてDataFrameを作成

import pandas as pd
import numpy as np

A = np.random.randint(10, size=(3, 6))
df = pd.DataFrame(A, columns=['xx_0', 'yy_0', 'zz_0', 'xx_1', 'yy_1', 'zz_1'])
df
#    xx_0  yy_0  zz_0  xx_1  yy_1  zz_1
# 0     1     7     2     0     8     4
# 1     9     4     4     3     6     0
# 2     3     4     9     5     8     2

'xx'を抽出したい文字列とする。
カラムの抽出にはブール値マスクを使ってみる。

データフレームをマスクするためのブール値配列を作成。リスト内包表記を使う。

mask = ['xx' in s for s in df.columns]
mask
# [True, False, False, True, False, False]

'xx' in sは変数sに文字列xxが含まれる場合True、そうでない場合はFalseを返す。

locメソッドでカラム側のスライスにマスクを指定して

df.loc[:, mask]
#    xx_0  xx_1
# 0     1     0
# 1     9     3
# 2     3     5

'xx'を含む列のみ抽出できた。locの代わりにilocでも良さそう。

0
2
2

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
2