2017-09-21 9 views
0

dictionarykeypandas列のstringsをそのvaluesに置き換えようとしています。ただし、各列には文が含まれています。したがって、まず、文章をトークン化し、その文中の単語が辞書内のキーと一致するかどうかを検出し、その文字列を対応する値に置き換える必要があります。辞書を使用してPandas列の文字列内の文字列を置き換えます

しかし、私はそれを得ることを続けているという結果。この問題に近づくためのより良い方法がありますか?

ここは私のMVCです。コメントでは、問題の発生場所を指定しました。

import pandas as pd 

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

ids = {'Id':['NYC','LA','UK'], 
     'City':['New York City','Los Angeles','United Kingdom']} 


df = pd.DataFrame(data) 
ids = pd.DataFrame(ids) 

def col2dict(ids): 
    data = ids[['Id', 'City']] 
    idDict = data.set_index('Id').to_dict()['City'] 
    return idDict 

def replaceIds(data,idDict): 
    ids = idDict.keys() 
    types = idDict.values() 
    data['commentTest'] = data['Comment'] 
    words = data['commentTest'].apply(lambda x: x.split()) 
    for (i,word) in enumerate(words): 
     #Here we can see that the words appear 
     print word 
     print ids 
     if word in ids: 
     #Here we can see that they are not being recognized. What happened? 
      print ids 
      print word 
      words[i] = idDict[word] 
      data['commentTest'] = ' '.apply(lambda x: ''.join(x)) 
    return data 

idDict = col2dict(ids) 
results = replaceIds(df, idDict) 

結果:

None 

私はpython2.7を使用していますが、私はdictをプリントアウトしていたときに、ユニコードのu'があります。

私の期待される結果は次のとおりです。

カテゴリー

コメント

タイプ

commentTest

Categories Comment Type commentTest 
0 animal The NYC tree is very big tree The New York City tree is very big 
1 plant The cat from the UK is small dog The cat from the United Kingdom is small 
2 object The rock was found in LA. rock The rock was found in Los Angeles. 

答えて

2

あなたがdictionary、その後replaceを作成することができます。

ids = {'Id':['NYC','LA','UK'], 
     'City':['New York City','Los Angeles','United Kingdom']} 

ids = dict(zip(ids['Id'], ids['City'])) 
print (ids) 
{'UK': 'United Kingdom', 'LA': 'Los Angeles', 'NYC': 'New York City'} 

df['commentTest'] = df['Comment'].replace(ids, regex=True) 
print (df) 
    Categories      Comment Type \ 
0  animal  The NYC tree is very big tree 
1  plant 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 The cat from the United Kingdom is small 
2  The rock was found in Los Angeles. 
+0

なぜ 'regex = True'ですか?ドキュメントから私はそれは偽であるべきです: "to_replaceと/または値を正規表現として解釈するかどうかこれがTrueの場合、to_replaceは文字列でなければなりません。そうでない場合、to_replaceはNoneでなければなりません。このパラメータは正規表現またはリスト、辞書、または正規表現の配列を含むことができます。 – pceccon

+0

@pceccon - 私の意見では、ドキュメントでは、それはより一般的な部分文字列を置換するために使用されていることに注意する必要があります。 – jezrael

関連する問題