在pandas数据帧中加入元组列表

2024-10-04 11:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加入一个数据帧中的元组列表。 我尝试过在数据帧中使用joinlambda实现这一点的几种方法

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连接方法有:

^{pr2}$

不管我做什么,我都会犯同样的错误。在

TypeError: sequence item 0: expected string, tuple found

我想要的回答是

[('A', 'B'),  ('B', 'C'),  ('C', 'B')]

在要输出文件的数据帧中

'A_B B_C C_B'

关于出什么问题有什么建议吗?在


Tags: the数据方法lambdafromposimportdata
1条回答
网友
1楼 · 发布于 2024-10-04 11:32:26

可以使用doublelist comprehension并将输出分配给column back:

所以不是:

data['taggedComment'].apply(lambda x: (' '.join(x)))

{cd2>在下面的方法中使用:

^{pr2}$

总而言之:

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 ._.

相关问题 更多 >