2017-02-19 5 views
0

私はDataFrame列のすべての要素を調べ、それらにカテゴリを割り当てる識別子関数を持っています。私が今持っているコードは、このようになります。Python - 正規表現をベクトル化して分類する

def fruit_replace(x): 
    fruit_quantity = re.search(r'(\\d+)quantity', x) 
    if 'apple' in x: 
     return 'green' 
    elif 'pear' in x: 
     return 'green' 
    elif 'cherry' in x: 
     return 'red' 
    elif 'banana' in x: 
     return 'yellow' 
    elif fruit_quantity != None: 
     return fruit_quantity.group(0) 

これをDataFrameのラムダ関数に適用し、結果を新しい列に割り当てます。残念ながら、fruit_quantityの検索が他の検索と異なるため、少し複雑です。

このような処理が行われるはずです。この

pd.DataFrame({'fruit_type': ['big apple', 'small cherry', 'peach 10quantity'], 
       'category': ['green', 'red', 10]}) 

の中へ

オリジナルDATAFRAME

pd.DataFrame({'fruit_type': ['big apple', 'small cherry', 'jerry 10quantity']}) 

このコードは、よりニシキヘビやパンダの方法で改善し、そしておそらくベクトル化することができれば私の質問はありますか?これを約500万行に適用する必要があり、これには時間がかかります。

多くの感謝!

+0

サンプルデータセット(5-7行)と、所望のデータセットを提供してください。 [再現性の良いパンダの例を作る方法](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)をお読みください。 – MaxU

答えて

1

あなたはstr.contains()方法と一緒にboolean indexingを使用することができます。

df['category'] = np.nan 

df.loc[df.fruit_type.str.contains(r'\b(?:apple|pear)\b'), 'category'] = 'green' 
df.loc[df.fruit_type.str.contains(r'\b(?:cherry)\b'), 'category'] = 'red' 
df.loc[df.fruit_type.str.contains(r'\b(?:banana)\b'), 'category'] = 'yellow' 
df.loc[df['category'].isnull() & (df.fruit_type.str.contains(r'\d+q')), 'category'] = \ 
    df.fruit_type.str.extract(r'(\d+)q', expand=False) 

結果:

In [270]: df 
Out[270]: 
     fruit_type category 
0   big apple green 
1  small cherry  red 
2 jerry 10quantity  10