SQLのcase whenと同じことをpandas.DataFrameに対して行う
pandas.DataFrameに対してSQLのcase whenと同じことをして、新しい列を作る方法がはいくつかあるようなので、まとめておく。
元データ
import pandas as pd import numpy as np df=pd.DataFrame({'fruit':['Strawberry','Apple', 'Peach', 'Banana', 'grapes']}) df
fruit | |
---|---|
0 | Strawberry |
1 | Apple |
2 | Peach |
3 | Banana |
4 | grapes |
上記が元データで、下記の「果物」という新しい列を加えたdataftameにしたい
fruit | 果物 | |
---|---|---|
0 | Strawberry | いちご |
1 | Apple | りんご |
2 | Peach | もも |
3 | Banana | ばなな |
4 | grapes | ぶどう |
numpy.where()
numpy.where()を使って新しい列を作成する方法。 個人的には比較的読みやすい書き方と感じる。ただしネストが深くなり、処理速度が遅い。データ量が少ない時は処理速度を気にしなくて良いので、読みやすいnumpy.where()を使うことが多い。
df['果物']=np.where(df['fruit']=='Strawberry', 'いちご', np.where(df['fruit']=='Apple', 'りんご', np.where(df['fruit']=='Peach', 'もも', np.where(df['fruit']=='Banana', 'ばなな', np.where(df['fruit']=='grapes', 'ぶどう', 'その他')))))
if文による関数作ってapply
処理速度が速い。ただし、個人的には読みにくいと感じる。データ量が多くelifの数が少ない場合は、処理速度を優先させたいのでこの方法を使うことが多い。
def func(x): if x=='Strawberry': return 'いちご' elif x=='Apple': return 'りんご' elif x=='Peach': return 'もも' elif x=='Banana': return 'ばなな' elif x=='grapes': return 'ぶどう' else: return 'その他' df['果物'] = df['fruit'].apply(func)
df.loc
処理速度はnumpy.where()よりは早く、if文による関数作ってapplyよりは少し遅い。一緒に仕事をする方が良くdf.locを使うようであればこの方法を使うことが多い。
df.loc[df['fruit'] == 'Strawberry', '果物'] = 'いちご' df.loc[df['fruit'] == 'Apple', '果物'] = 'りんご' df.loc[df['fruit'] == 'Peach', '果物'] = 'もも' df.loc[df['fruit'] == 'Banana', '果物'] = 'ばなな' df.loc[df['fruit'] == 'grapes', '果物'] = 'ぶどう'
3つの方法を記載したが、それぞれ良さがあり適宜適切な方法を選択したいところ。