0
2

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

【pandas】DataFrameでifっぽいことをやる

Posted at

locを使って、特定の条件であれば値を追加したい

下記のようなDataFrameのnameカラムがひらがなのみ、カタカナのみだった場合、kindカラムに「ひらがな」「カタカナ」と文字列を入れたい。

   id   name
0   1  あいうえお
1   2  かきくけこ
2   3  サシスセソ

   id   name  kind
0   1  あいうえお  ひらがな
1   2  かきくけこ  ひらがな
2   3  サシスセソ  カタカナ

このように修正したい

コード

ひらがな・カタカナの正規表現にあてて、trueだった場合値を入れるような形

import pandas as pd
import numpy as np
import re

df = pd.DataFrame(
    data={
        'id': [1, 2, 3],
        'name': ['あいうえお', 'かきくけこ', 'サシスセソ']
    }
)

pattern = re.compile('^[\u3040-\u309F]+$')
df.loc[df['name'].str.match(pattern), 'kind'] = 'ひらがな'

pattern = re.compile('^[\u30A0-\u30FF]+$')
df.loc[df['name'].str.match(pattern), 'kind'] = 'カタカナ'
print(df)

pandas.DataFrame.locびドキュメントはこちら

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?