2017-09-21 12 views
1

pandasデータフレーム内の特定の値を置き換えるには、厳密なregular expressionを書く必要があります。これは私がhereと投稿した質問を解決した後に提起された問題です。パンダの厳密な正規表現は置き換えます

問題は、.replace(idsToReplace, regex=True)が厳密ではないことです。

NY : New York 
NYC : New York City 

、我々はIDを交換されているコメントは、次のとおりです:iDsToReplaceがある場合はそのため

My cat from NYC is large. 

結果の応答は次のとおりです。

My cat from New York is large. 

内の神託の方法はありますpandasreplaceregular expressionNYCと一致させ、NYと一致させないようにする機能がありますか?

+0

正規表現での厳密性という概念がありません、それはちょうどあなたがそれを伝えるものと一致します。あなたは '\ b'単語境界を探しているかもしれません。 – Aaron

+0

申し訳ありませんが、dictが 'd = {'NYC': 'New York City'、 'NY': 'ニューヨーク市からの私の猫は大きいです。ニューヨーク '} '? – jezrael

+0

問題は、Word NYCがNYCではなくNYによってキャプチャされていたことでした。従って正しい答えは:「ニューヨーク市の私の猫は大きい」私はいくつかのテストを行っていますが、これまでのところ、あなたの下の答えが 'bounds'と一緒に働いているようです。 – owwoow14

答えて

0

dictの各キーにword boundariesため\bを追加します。

d = {'UK': 'United Kingdom', 'LA': 'Los Angeles', 'NYC': 'New York City', 'NY' : 'New York'} 

data = {'Categories': ['animal','plant','object'], 
    'Type': ['tree','dog','rock'], 
     'Comment': ['The NYC tree is very big', 'NY The cat from the UK is small', 
        'The rock was found in LA.'] 
} 

d = {r'\b' + k + r'\b':v for k, v in d.items()} 

df = pd.DataFrame(data) 

df['commentTest'] = df['Comment'].replace(d, regex=True) 
print (df) 
    Categories       Comment Type \ 
0  animal   The NYC tree is very big tree 
1  plant NY The cat from the UK is small dog 
2  object  The rock was found in LA. rock 

             commentTest 
0     The New York City tree is very big 
1 New York The cat from the United Kingdom is small 
2     The rock was found in Los Angeles. 
関連する問題