4
6

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 5 years have passed since last update.

Python Pandasにおいて文字列処理の方法

Posted at

本日はPythonのライブラリのひとつpandasを使ってデータ分析を行なった。
pandasにおいてデータフレームの中で特定の文字列を含む行や列のみ抽出したいときに役に立つ関数について列挙する。

目次

・isin
・contains

pd.Series.str.contains関数

これはSeriesに適応できる関数である。DataFrameには使えないので、DataFrameからひとつずつSeriesを抽出して作る必要がある。

以下は適当に作ったデータフレームとする。

data = pd.DataFrame(
    {'animal': ['dog', 'cat', 'wolf', 'bat'],
     'habitat': ['USA', 'Canada', 'Japan', 'Russia']})

animal habitat
0 dog USA
1 cat Canada
2 wolf Japan
3 bat Russia
df[df['animal'].str.contains('at')]

以下のようにanimalで文字列'at'を含むデータフレームが出力される:

animal habitat
0 cat Canada
1 bat Russia
df[df['animal'].str.contains('an')]

これはこのように出力される

animal habitat
0 cat Canada
1 wolf Japan

contains関数は引数にstrしか受け付けないので、listなど複数のstrを渡したい場合次のisin関数を使うことになる。

isin関数

上のは結構使えるが、複数の単語を含むデータフレームを抽出したい場合、isin関数を使おう。
isin関数はlist系の引数を受け付けるので、numpyのarrayなども渡すことが可能となる。
ただし、containsとは違って文字列を含む値の抽出ではなく、その文字列と==の関係になるものを抽出してしまうことに注意!

df[df.['animal'].isin(['cat', 'wolf'])]

出力:

animal habitat
0 cat Canada
1 wolf Japan

以上!str系にはcatなどの文字列を結合する関数もあり、これも結構有能だが、また今度説明します。

4
6
0

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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?