【发布时间】:2018-03-02 17:18:37
【问题描述】:
我正在尝试使用dictionary key 将pandas 列中的strings 替换为其values。但是,每一列都包含句子。因此,我必须先对句子进行分词,并检测句子中的某个单词是否与我的字典中的某个键对应,然后将字符串替换为对应的值。
但是,我继续得到它的结果没有。有没有更好的 Pythonic 方法来解决这个问题?
这是我目前的 MVC。在 cmets 中,我指定了问题发生的位置。
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' 的Unicode。
我的预期结果是:
类别
评论
类型
评论测试
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.
【问题讨论】:
标签: python pandas dictionary dataframe replace