我想加入数据框中的元组列表。 我已经尝试了几种在数据框中使用 join 和 lambda
import pandas as pd
from nltk import word_tokenize, pos_tag, pos_tag_sents
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.']}
def posTag(data):
data = pd.DataFrame(data)
comments = data['Comment'].tolist()
taggedComments = pos_tag_sents(map(word_tokenize,comments))
data['taggedComment'] = taggedComments
print data['taggedComment']
data['taggedComment'].apply(lambda x: (' '.join(x)))
return data
taggedData = posTag(data)
print data
我尝试过的其他一些 tuple 连接方法是:
(' '.join(['_'.join(x) for x in data['taggedComment']]))
[''.join(x) for x in data['taggedComment']]
['_'.join(str(x)) for x in data['taggedComment']]
无论我做什么,我都会遇到同样的错误。
TypeError: sequence item 0: expected string, tuple found
如果对于每个列表,我想要的响应
[('A', 'B'), ('B', 'C'), ('C', 'B')]
在 outPutFile 的数据框中
'A_B B_C C_B'
关于哪里出了问题有什么建议吗?
请您参考如下方法:
您可以使用双重列表理解并将输出分配给列返回:
所以代替:
data['taggedComment'].apply(lambda x: (' '.join(x)))
在您的 posTag(data) 方法中使用以下内容:
data['taggedComment'] = [' '.join(['_'.join(y) for y in x]) for x in data['taggedComment']]
taggedData = posTag(data)
print (taggedData)
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
taggedComment
0 The_DT NYC_NNP tree_NN is_VBZ very_RB big_JJ
1 NY_NNP The_DT cat_NN from_IN the_DT UK_NNP is_...
2 The_DT rock_NN was_VBD found_VBN in_IN LA_NNP ._.
一起:
def posTag(data):
data = pd.DataFrame(data)
comments = data['Comment'].tolist()
print (pos_tag_sents(map(word_tokenize, comments)))
taggedComments = pos_tag_sents(map(word_tokenize, comments))
data['taggedComment'] = [' '.join(['_'.join(y) for y in x]) for x in taggedComments]
return data
taggedData = posTag(data)
print (taggedData)
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
taggedComment
0 The_DT NYC_NNP tree_NN is_VBZ very_RB big_JJ
1 NY_NNP The_DT cat_NN from_IN the_DT UK_NNP is_...
2 The_DT rock_NN was_VBD found_VBN in_IN LA_NNP ._.
