0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pandasでカラムが特定の文字列を含むか1行ずつチェックし、その行のみを抽出

Last updated at Posted at 2022-05-01
import pandas

df = pandas.read_csv('sample.csv')
df2 = pandas.DataFrame({})

for index, row in df.iterrows():
    if row['x'] in ("b", "e"): # check
        df2 = df2.append({'x': row['x'], 'y': row['y'], 'z': row['z']}, ignore_index=True)

print(df2)
sample.csv
	x	y	z
0	a	foo	1
1	b	bar	2
2	c	baz	3
3	b	foo	4
	x	y	z
1	b	bar	2

(2022/5/3 編集追記)

上述のfor文は、カラムが特定の値を持っていた場合に別の処理を呼び出したいため記述しましたが、シンプルに特定の文字列を含む行を抽出する場合には下記のような書き方がシンプルで良いと思いました。

@WolfMoon2 氏よりコメントにて教えていただきました。

df[(df['x'] == 'b') & (df['y'] == 'bar')]

ref: https://qiita.com/akkiii/items/ed365fc97ff012043ed4#comment-3d70369003280f363c28

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?