熊猫:将值分配给元素列表的数据框(如果存在)

时间:2019-08-28 14:36:25

标签: python pandas

我正在尝试从列表中的元素分配值,如果它将此子字符串startswith分配给pandas数据框列

代码:

searchwords = ['harry','harry potter','lotr','secret garden']

l1 = [1, 2, 3,4,5]
l2 = ['Harry Potter is a great book',
      'Harry Potter is very famous',
      'I enjoyed reading Harry Potter series',
      'LOTR is also a great book along',
      'Have you read Secret Garden as well?'
]
df = pd.DataFrame({'id':l1,'text':l2})
df['text'] = df['text'].str.lower()

数据预览:

   id   text
0   1   harry potter is a great book
1   2   harry potter is very famous
2   3   i enjoyed reading harry potter series
3   4   lotr is also a great book along
4   5   have you read secret garden as well?

尝试:

df.loc[df['text'].str.startswith(tuple(searchwords)),'tags'] if (df['text'].str.startswith(tuple(searchwords))) == True else np.NaN

错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().我在做什么错?我以为您可以在if / else逻辑中分配值== True

寻找这样的输出:

   id   text                                     tags
0   1   harry potter is a great book             harry;harry potter
1   2   harry potter is very famous              haryy;harry potter
2   3   i enjoyed reading harry potter series    NaN
3   4   lotr is also a great book along          lotr
4   5   have you read secret garden as well?     NaN

2 个答案:

答案 0 :(得分:1)

尝试使用apply

df['tags'] = df.text.apply(
    lambda text: [searchword for searchword in searchwords if text.startswith(searchword)]
)

这为您提供了tags列,其中包含各个标签的列表,如下所示: enter image description here

如果您更喜欢nan而不是空白列表[],则可以执行第二步。

df['tags'] = df.tags.apply(
    lambda current_tag: float('nan') if len(current_tag)==0 else current_tag
)

答案 1 :(得分:0)

这是另一个版本

df["tags"] = df["text"].str.split(" ").apply(lambda x: list(set(x) & set(
        searchwords)))

如果您想要Nan而不是空白列表,请添加以下内容

import numpy as np 

df['tags'] = df['tags'].apply(lambda x: np.nan if len(x)==0 else x)