首页 > 解决方案 > 创建一个内容为集合的 pandas DataFrame 列

问题描述

我遇到了熊猫问题。

所以这是我的数据框:

user    page_number   page_parts_of_speech
Anne    1             [('Hi', NP), ('my', PP), ('name', NN), ('is', VB), ('Anne', NP)]
John    2             [('Hi', NP), ('my', PP), ('name', NN), ('is', VB), ('John', NP)]

我想添加一个名为 的新列,set_of_parts_of_speech其中包含一个集合,该集合包含该parts_of_speech列中所有与 NP 元组的单词。

示例输出为:

    user    page_number   page_parts_of_speech    set_of_parts_of_speech                           
    Anne    1             [('Hi', NP), ('my', PP),  ['Hi', 'Anne']
    ('name', NN), ('is', VB), ('Anne', NP)]
    John    2             [('Hi', NP), ('my', PP),  ['Hi', 'John']
    ('name', NN), ('is', VB), ('John', NP)]

set_of_parts_of_speech 列包含一个实际集合非常重要。

对此问题的任何帮助将不胜感激。

标签: pythonpandasset

解决方案


与列表推导一起使用apply按条件过滤:

print (type(df.loc[0, 'page_parts_of_speech']))
<class 'list'>

f = lambda x: set([y[0] for y in x if y[1] == 'NP'])
df['set_of_parts_of_speec'] = df['page_parts_of_speech'].apply(f)
print (df)
   user  page_number                               page_parts_of_speech  \
0  Anne            1  [(Hi, NP), (my, PP), (name, NN), (is, VB), (An...   
1  John            2  [(Hi, NP), (my, PP), (name, NN), (is, VB), (Jo...   

  set_of_parts_of_speec  
0            {Hi, Anne}  
1            {Hi, John}  

推荐阅读